【问题标题】:java.net.ConnectException/java.net.ConnectException depending on normal run or debug modejava.net.ConnectException/java.net.ConnectException 取决于正常运行或调试模式
【发布时间】:2016-04-03 16:58:45
【问题描述】:

您好,我正在尝试使用 IP 和端口向服务器发送二进制消息:

192.168.2.101:10001

套接字每 50 条消息重新打开一次。

如果我正常运行应用程序,我会在第 5 行收到 java.net.ConnectException,即使我可以 ping 和远程登录服务器。

如果我调试应用程序,我会在不同的行 (11) 收到 java.net.SocketException,有时第一条消息似乎也没有任何错误。

private void sendMessage(String message, int relaisId, long timestamp) {

    try {
        if (connCount > 50) {
            s = new Socket(ip, port); //RUN NORMALLY: java.net.ConnectException: Connection refused: connect
            connCount=0;
        }
        outputStream = s.getOutputStream();

        outputStream.write(message.getBytes());
        outputStream.write(new byte[]{0});//DEBUG: java.net.SocketException: Connection reset by peer: socket write error
        outputStream.flush();
        connCount++;
    } catch (UnknownHostException ex) {
        logger.error("Host not found: " + ip + ":" + port, ex);
        connCount=51;
        retryMessage(message, relaisId, timestamp);// basically sleep 3s then call sendMessage
    } catch (IOException ex) {
        logger.error("Error at Relais No. " + relaisId + ": " + ip + ":" + port, ex);
        connCount=51;
        retryMessage(message, relaisId, timestamp); // basically sleep 3s then call sendMessage
    } finally {
        try {
            if (connCount > 50 && s != null) {
                s.close();                    
            }
        } catch (IOException ex) {
            logger.error("IOException", ex);
        }
    }
}

非常感谢任何帮助或分析工具:)

【问题讨论】:

    标签: java sockets connection outputstream tcp-ip


    【解决方案1】:

    我找到了解决方案。在我的程序中,不同的线程通过给定的 IP 和端口向外部硬件组件发送消息。 出现这个错误是因为一个线程意外启动了两次,使用相同的 IP 地址和端口,导致使用相同的套接字时发生时序冲突。

    更奇怪的是,这个错误在更换服务器机器时开始永久发生,之前只是偶尔出现,我们认为这是网络通信中的噪音。

    希望这对未来的任何人都有帮助:)

    【讨论】:

      猜你喜欢
      • 2015-07-02
      • 1970-01-01
      • 1970-01-01
      • 2013-02-02
      • 2021-05-14
      • 1970-01-01
      • 2015-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多