我能够将UDP数据报从我的客户端发送到我的服务器并接收它 我无法从服务器向客户端发送数据报。
什么都没发生。 我只看到: " Hello Server"在服务器端,但我不明白: " Hello Client"在客户端。
final int PACKETSIZE = 100;
//CLIENT
byte[] newData = "Hello Server".getBytes();
DatagramPacket newPacket = new DatagramPacket(newData, newData.length, packet.getAddress(), packet.getPort());
// Send it
socket.send(newPacket);
// Set a receive timeout, 2000 milliseconds
socket.setSoTimeout(2000);
// Prepare the packet for receive
packet.setData(new byte[PACKETSIZE]);
// Wait for a response from the server
socket.receive(packet);
// Print the response
System.out.println("RECEIVED MESSAGE FROM SERVER: " + new String(packet.getData()));
//SERVER
int port = Integer.parseInt("1024");
socket = new DatagramSocket(port);
System.out.println("SERVER STARTED ON UDP PORT: " + port);
while (true) {
// Create a packet
packet = new DatagramPacket(new byte[PACKETSIZE], PACKETSIZE);
// Receive a packet (blocking)
socket.receive(packet);
// Print the packet sent from the client
System.out.println(packet.getAddress() + " " + packet.getPort() + ": " + new String(packet.getData()));
// Create a new packet to send back to the client
byte[] newData = "Hello Client".getBytes();
DatagramPacket newPacket = new DatagramPacket(newData, newData.length, packet.getAddress(), packet.getPort());
// Return the packet to the sender (the client)
socket.send(newPacket);
}
答案 0 :(得分:0)
搞定了。 重复使用相同的数据包。