Java中实现UDP通信可以使用Java的java.net包中的DatagramSocket和DatagramPacket类。
DatagramSocket socket = new DatagramSocket(8888);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
byte[] receivedData = packet.getData();
String message = "Hello, UDP!";
byte[] sendData = message.getBytes();
InetAddress address = InetAddress.getByName("localhost");
int port = 8888;
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, address, port);
socket.send(sendPacket);
socket.close();
完整示例代码如下:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UdpExample {
public static void main(String[] args) {
try {
// 创建DatagramSocket对象,指定端口号
DatagramSocket socket = new DatagramSocket(8888);
// 创建接收数据的字节数组和DatagramPacket对象
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
// 接收数据
socket.receive(packet);
// 获取接收到的数据
byte[] receivedData = packet.getData();
String receivedMessage = new String(receivedData, 0, packet.getLength());
System.out.println("Received message: " + receivedMessage);
// 准备发送数据
String message = "Hello, UDP!";
byte[] sendData = message.getBytes();
InetAddress address = InetAddress.getByName("localhost");
int port = 8888;
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, address, port);
// 发送数据
socket.send(sendPacket);
// 关闭DatagramSocket
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
注意:在实际应用中,通常需要使用多线程来实现同时进行接收和发送操作。