【问题标题】:Socket does not receive messages套接字不接收消息
【发布时间】:2013-02-22 10:01:49
【问题描述】:

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

【问题讨论】:

    标签: java linux sockets udp


    【解决方案1】:

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

    【讨论】:

    • 你是对的 - 服务器在我的机器上运行良好 - 我测试了很多次。但是当我将它转移到远程服务器时,它就停止了任何操作。我在远程服务器上运行了 tcpdump - 更新我的问题以显示结果。
    • 所以端口有点接收消息......但不是程序
    【解决方案2】:

    好的,问题已解决。问题是:

    Red Hat linux 上的防火墙,我成功关闭了所需端口的防火墙。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-28
      • 1970-01-01
      • 1970-01-01
      • 2017-09-04
      • 2012-01-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多