0

我编写了一个简单的客户端和简单的 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
4

2 回答 2

1

Ok, question resolved. The problem was:

FIREWALL on Red Hat linux, which I successfully switched off for the required port.

于 2013-02-22T11:51:09.657 回答
1

我用 netcat 在本地测试了你的服务器代码,它工作得很好,所以问题必须出在其他地方。您确定您实际上是在发送 UDP 数据包吗?您是否在远程服务器上运行了 tcpdump?否则,您的数据包可能会被过滤。

于 2013-02-22T10:42:05.283 回答