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();
}
}
}
注意:在實際應用中,通常需要使用多線程來實現同時進行接收和發送操作。