我编写了一个简单的客户端和简单的 udp 服务器,需要从特定端口读取字符串消息。这是UDP套接字:
public class UDPServer {
// boolean variable defines if the infinite loop
// in startServer() runs or not
private boolean isSwitched = false;
private DatagramSocket socket = null;
public UDPServer(int port) throws SocketException {
socket = new DatagramSocket(port);
Logger.getLogger(Main.class.getName()).log(Level.INFO, "Server started! Bound to port: " + port);
}
//this method start the server and switches on the infinite loop to
// listen to the incoming UDP-packets
public void startServer() throws IOException {
this.isSwitched = true;
Logger.getLogger(Main.class.getName()).log(Level.INFO, "Server starts listening!");
while (isSwitched) {
byte[] size = new byte[30];
DatagramPacket dp = new DatagramPacket(size, size.length);
try {
System.out.println("Debug: receive loop started!");
socket.receive(dp);
System.out.println("Debug: Packet received after socket.receive!");
Thread requestDispatch = new Thread(new Request(dp.getData()));
requestDispatch.start();
} catch (SocketException ex) {
Logger.getLogger(Main.class.getName()).log(Level.INFO, "Stops listening on specified port!");
}
}
}
// this method stops the server from running
public void stopServer() {
this.isSwitched = false;
socket.close();
Logger.getLogger(Main.class.getName()).log(Level.INFO, "Server is shut down after last threads complete!");
}
}
我将它部署在远程服务器上并打开程序。服务器打印出它开始侦听,因此它到达 socket.receive() 阶段。然后我从远程客户端发送一条 UDP 消息。但什么也没有发生。udp 服务器没有进一步移动 - 它只是保持并且似乎没有收到任何消息。我尝试使用 tcpdump 调试端口,它显示消息到达所需的端口。但java程序似乎没有收到它们。当我在远程服务器上发出此命令时:
tcpdump udp port 50000
并发送一些它所写的数据包:
12:53:40.823418 IP x.mobile.metro.com.42292 > y.mobile.metro.com.50000: UDP, length 28
12:53:43.362515 IP x.mobile.metro.com.48162 > y.mobile.metro.com.50000: UDP, length 28