客户端无法从服务器接收 UDP 数据报
Posted
技术标签:
【中文标题】客户端无法从服务器接收 UDP 数据报【英文标题】:Client can't receive UDP datagram from the server 【发布时间】:2014-04-02 23:13:31 【问题描述】:但是,我可以将 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);
【问题讨论】:
【参考方案1】:搞定了。 正在重复使用同一个数据包。
【讨论】:
以上是关于客户端无法从服务器接收 UDP 数据报的主要内容,如果未能解决你的问题,请参考以下文章