UDP

UDP 服务端

Java 中使用 DatagramSocket 类来进行 UDP 通信。其构造函数如下:

java.net.DatagramSocket.DatagramSocket(int port) 
                        throws SocketException
  • port: 代表本端要绑定的端口号。

UDP 通信中在服务端和客户端收发的数据叫“包”,用 DatagramPacket 类的对象表示。“包” 中含有一个字节数组。

用以接受数据的包常用如下构造函数:

java.net.DatagramPacket.DatagramPacket(byte[] buf, 
                                    int offset, int length)

用以发送数据的包常用如下构造函数:

java.net.DatagramPacket.DatagramPacket(byte[] buf, 
                                    int length, 
                                    InetAddress address, 
                                    int port)
try {
    DatagramSocket serverSocket = new DatagramSocket(9527);
    DatagramPacket rcvPacket = new DatagramPacket(new byte[1024], 0, 1024);
            
    UDPClient client = new UDPClient();
    client.start();

    serverSocket.setSoTimeout(2000);
    serverSocket.receive(rcvPacket);

    String str = new String(rcvPacket.getData(), 0, rcvPacket.getLength());
    System.out.println(str);
}
catch (SocketException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

UDP 客户端

try
{
    DatagramSocket socket = new DatagramSocket(1234);
    socket.setSoTimeout(2000);
            
    byte[] sndbuf = "HelloWorld".getBytes();
    DatagramPacket sndPacket = new DatagramPacket(sndbuf, sndbuf.length, InetAddress.getByName("127.0.0.1"), 9527);
            
    socket.send(sndPacket);
}
catch (SocketException e) {
    e.printStackTrace();
} 
catch (UnknownHostException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

你可能感兴趣的:(UDP)