我编写了一个简单的客户端和简单的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-server不再移动 - 它只是保持并且似乎没有收到任何消息 . 我尝试使用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
2 回答
我用netcat在本地测试了你的服务器代码,它运行得很好,所以问题必须在其他地方 . 你确定你实际上是在发送UDP数据包吗?你在远程服务器上运行tcpdump了吗?如果没有,可能会过滤您的数据包 .
好的,问题解决了 . 问题是:
Red Hat linux上的防火墙,我成功关闭了所需的端口 .