java.net.ConnectException/java.net.ConnectException 取决于正常 运行 或调试模式

java.net.ConnectException/java.net.ConnectException depending on normal run or debug mode

您好,我正在尝试将二进制消息发送到具有 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);
        }
    }
}

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

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

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

希望这对以后的任何人都有帮助:)