如何实现UDP协议下的数据传输和接收?代码举例讲解

UDP协议是无连接的,提供不可靠的数据报服务。实现UDP数据传输和接收主要有以下步骤:

  1. 发送方创建DatagramSocket,指定发送端端口。
DatagramSocket socket = new DatagramSocket(8000);
  1. 构建DatagramPacket,包含发送数据和接收方地址及端口。
byte[] data = "Hello".getBytes();
InetAddress address = InetAddress.getByName("127.0.0.1");
int port = 9000;
DatagramPacket packet = new DatagramPacket(data, data.length, address, port);
  1. 发送方调用DatagramSocket的send方法发送数据报。
socket.send(packet);  
  1. 接收方创建DatagramSocket,指定接收端端口。
DatagramSocket socket = new DatagramSocket(9000);
  1. 接收方创建DatagramPacket用于接收数据。
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
  1. 接收方调用DatagramSocket的receive方法接收数据报。
socket.receive(packet);
  1. 接收方可以通过DatagramPacket的getAddress、getPort等方法获取发送方地址和端口。
InetAddress address = packet.getAddress();
int port = packet.getPort();

一个简单示例:
发送方:

public class UDPSender {
    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(8000);
        byte[] data = "Hello".getBytes();
        InetAddress address = InetAddress.getByName("127.0.0.1");
        DatagramPacket packet = new DatagramPacket(data, data.length, address, 9000);
        socket.send(packet);
        socket.close();
    } 
}

接收方:

public class UDPReceiver {
    public static void main(String[] args) throws IOException { 
        DatagramSocket socket = new DatagramSocket(9000);
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
        socket.receive(packet);
        String data = new String(packet.getData());
        System.out.println(data);
        socket.close();
    }
}

运行结果:

Hello