Utilice UDP para enviar datos en una dirección

Es mejor ejecutar primero el archivo .java del receptor y luego ejecutar el del remitente. Para no causar pérdida de datos porque el receptor no ha comenzado a recibir datos, el remitente los enviará primero.

remitente

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/*
* UDP传输的发送端:
1 建立udp的socket对象
2.将要发送的数据封装成数据包
3.通过udp的socket对象,将数据包发送出
4.释放资源
* */
public class SendData {//这里只实现单方向传数据A->B

    public static void main(String[] args) throws IOException {
        //建立udp的socket对象,并指定本主机要用哪个端口(1-65535)发送数据
        DatagramSocket socket = new DatagramSocket(69);

        //用键盘循环输入要发送的内容
        BufferedReader bufferin = new BufferedReader(new InputStreamReader(System.in));
        String s;
        while ((s = bufferin.readLine()) != null) {
            byte[] bytes = s.getBytes();//把字符串->字节
            //在给定主机名的情况下,返回其IP地址的对应对象
            InetAddress targerIP = InetAddress.getByName("127.0.0.1");//目的IP
            //将要发送的数据封装成数据包,目的端口8888
            DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length, targerIP, 8888);
            //再把数据报输到socke的send方法里,发送出去,
            socket.send(packet);
            if (s.equals("886")) {//发送方发送886,说明数据发送完毕,接收方也可以停止接收
                break;
            }
        }
        socket.close();
    }
}

receptor

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketAddress;

/*
* 1.建立udp的socket对象.
2.创建用于接收数据的数据报包,通过socket对象的receive方法接收数据
3.通过数据包对象的功能来完成对接收到数据进行解析.
4.可以对资源进行释放
* */
public class ReceiveData {
    public static void main(String[] args) throws IOException {
        //建立udp的socket对象,输入本主机用来接收数据的端口
        DatagramSocket socket = new DatagramSocket(8888);
        // 创建充当缓冲区的字节数组
        byte[] bytes = new byte[1024];
        //让数据报包的缓冲区指针指向bytes
        DatagramPacket receivePacket = new DatagramPacket(bytes, 0, bytes.length);
        //接收数据,送到缓冲区
        while (true) {
            socket.receive(receivePacket);//receive是阻塞方法,在接收到数据报前一直阻塞
            // 解析数据报包
            byte[] data = receivePacket.getData();//得到缓冲区所有数据,相当于data=bytes
            int length = receivePacket.getLength();//返回缓冲区发送或接收到的数据长度
            int offset = receivePacket.getOffset();//返回缓冲区发送或接收到的数据偏移量
            String s = new String(data, offset, length);
            //另解,直接用bytes打印结果
            // String s = new String(bytes, 0, bytes.length);bytes的有效数据长度应该换成上面的length
            System.out.println(s);

            //从数据报包里获取源ip和源端口,如果是在发送方获得目的IP和目的端口号
           /* 方式1
            InetAddress sourceIP = receivePacket.getAddress();
            int port = receivePacket.getPort();
            System.out.println("接收到了来自"+ sourceIP +"/" + port +":"+s);
            方式2 获得IP+端口
            SocketAddress socketAddress = receivePacket.getSocketAddress();
            System.out.println("接受到了来自" + socketAddress + ":" + s);
            */

            if (s.equals("886")) {//如果发送方发送886,接收停止
                break;
            }
        }
        //关闭资源
        socket.close();
    }
}

 

Supongo que te gusta

Origin blog.csdn.net/qq_43496435/article/details/114217823
Recomendado
Clasificación