java网络编程– udp通信

java
Author

dd21

Published

December 5, 2022

客户端发送

package cn.usts.edu.lesson04;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UdpClientDemo01 {
    public static void main(String[] args) throws Exception{
        // 建立socket连接
        DatagramSocket socket = new DatagramSocket();
        // 建立一个数据包
        String msg = "hello udp application";
        int port=9999;
        InetAddress IP = InetAddress.getByName("127.0.0.1");
        // 字节数据,字节数据长度,目的ip,目的端口
        DatagramPacket datagramPacket = new DatagramPacket(msg.getBytes(),msg.getBytes().length,IP,port);
        // 发送
        socket.send(datagramPacket);
        // 关闭
        socket.close();
    }

}

服务端接收

package cn.usts.edu.lesson04;



import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UdpServerDemo01 {
    public static void main(String[] args) throws Exception {
        // 发放端口
        DatagramSocket socket = new DatagramSocket(9999);
        // 接收数据
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
        // 接收
        socket.receive(packet);
        // 输出
        System.out.println(new String(packet.getData(), 0, packet.getLength()));
        // 关闭
        socket.close();

    }
}