我在哪里可以找到有关Java的UDP的详细信息以及如何建立基本的UDP通信?
答案 0 :(得分:5)
This page提供有关如何创建UPD服务器和客户端的详细信息。
从本质上讲,您可以像这样创建一个服务器:
// Setup the socket
DatagramSocket socket = new DatagramSocket(12345);
// Receive a packet
byte[] buffer = new byte[512];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
// Do something with the data in the buffer
// and if necessary receive more packets
// Close the socket
socket.close();
在客户端一侧,您可以发送如下数据包:
// Create a socket
DatagramSocket socket = new DatagramSocket();
// Create a buffer and fill it with your data
byte[] buffer = new byte[512];
...
// Send the packet
InetAddress address = InetAddress.getByName("127.0.0.1");
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, 12345);
socket.send(packet);
// Close the socket
socket.close();