UDP网络编程的接受与发送信息

/发送端B===>可以接受数据
public class UDPSenderB {
    public static void main(String[] args) throws IOException {
        //创建一个DatagramSocket 对象,准备发送和接受数据
        DatagramSocket socket = new DatagramSocket(9998);
        //将需要发送的数据,封装到DatagramPacket对象
        byte[] data = "hello “明天吃火锅~".getBytes();
        DatagramPacket packet = new DatagramPacket(data, 0, data.length, InetAddress.getLocalHost(), 9999);
        socket.send(packet);

        //现在接受A发送的信息
        data = packet.getData();
        int len = packet.getLength();
        packet = new DatagramPacket(data, data.length);
        socket.receive(packet);
        String s = new String(data,0,len);
        System.out.println(s);

        System.out.println("UDPB端已经退出~");
        //关闭资源
        socket.close();
    }
}
public class UDPReceiverA {
    public static void main(String[] args) throws IOException {
        //1.创建一个DatagramSocket 对象,准备在9999接收数据
        DatagramSocket socket = new DatagramSocket(9999);
        //2.构建一个DatagramPacket对象,准备接受数据
        //一个数据包最大为64K===>2^16-1
        byte[] buf = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        //3.调用接受方法,将通过网络传输的DatagramPacket对象
        //填充到packet对象
        System.out.println("正在等待接收数据...");
        socket.receive(packet);

        //现在将数剧进行解包
        int len = packet.getLength();
        byte[] bytes = packet.getData();
        String s = new String(bytes,0,len);
        System.out.println("接收到的数据为:"+s);

        //现在发送数据
        byte[] bytes1 = "好的,明天见!".getBytes();
        DatagramPacket packet1 =new DatagramPacket(bytes1,0,bytes1.length, InetAddress.getLocalHost(),9998);
        socket.send(packet1);

        System.out.println("UDPA端已经退出~");
        //关闭数据流
        socket.close();
    }
}

UDP网络编程的接受与发送信息_第1张图片 

UDP网络编程的接受与发送信息_第2张图片

你可能感兴趣的:(韩顺平java习题,网络,udp,网络协议)