import java.net.*;
public class UdpClient {
public static void main(String[] args) throws Exception {
// 定义服务器地址和端口号
String serverAddress = "127.0.0.1";
int serverPort = 8888;
// 创建数据包对象并设置要发送的消息内容
byte[] sendData = "Hello Server!".getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getByName(serverAddress), serverPort);
// 创建UDP Socket对象
DatagramSocket socket = new DatagramSocket();
try {
// 向服务器发送数据包
socket.send(sendPacket);
// 接收从服务器返回的数据包
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
socket.receive(receivePacket);
// 打印服务器返回的消息内容
System.out.println("Received message from server: " + new String(receivePacket.getData(), 0, receivePacket.getLength()));
} finally {
// 关闭socket连接
socket.close();
}
}
}