简体   繁体   English

Java Socket即使读取超时也不会解除阻止

[英]Java Socket doesn't unblock even with read timeout

I have an application to write the request data over socket and read the response. 我有一个应用程序可以通过套接字写入请求数据并读取响应。

Some times Host doesn't respond to request and my code blocks, even though I'm using a read timeout. 有时,即使我使用读取超时,主机也不会响应请求和我的代码块。

There is no way to clear it manually and it require system to be rebooted or restart on the server handler required. 无法手动清除它,并且需要重新启动系统或在所需的服务器处理程序上重新启动。

Here is the code used. 这是使用的代码。 Connection appears to block at objBufferedInputStream.read(..) 连接似乎在objBufferedInputStream.read(..)objBufferedInputStream.read(..)

Socket clientSocket = new Socket(objInetAddress, hostPort);
clientSocket.setKeepAlive(true);
clientSocket.setReceiveBufferSize(8192);
clientSocket.setSendBufferSize(8192);
clientSocket.setSoTimeout(waitTimeBeforeSocketClose * 1000);
objBufferedInputStream = new BufferedInputStream(clientSocket
                    .getInputStream());
.......
objBufferedOutputStream.write(message, 0, message.length);
objBufferedOutputStream.flush();

while (bytesLeft > 0 && bytesread > -1) {
        try {
            bytesread = objBufferedInputStream.read(data, 4096 - bytesLeft, 1);             
        } catch (IOException e) {
            objLogger.writeException(e);
            try {
                objBufferedInputStream.close();
            } catch (IOException e1) {
                objLogger.writeException(e1);

                return null;
            }
            return null;
        }
        bytesLeft -= bytesread;
    }
    return data;

} }

Please advise whether this is expected behavior when the host doesn't respond or hold the response. 请告知主机不响应或保持响应时这是否是预期的行为。

Please advise whether there is alternate approach. 请告知是否有其他方法。

Either: 或者:

  1. waitTimeBeforeSocketClose is zero, so you are blocking indefinitely, or waitTimeBeforeSocketClose为零,因此您将无限期阻塞,或者

  2. It is non-zero, so you're getting a SocketTimeoutException inside your loop, and ignoring it, so you spin forever. 它是非零值,因此您在循环内获取SocketTimeoutException并忽略它,因此您将永远旋转。 Add a separate catch block for SocketTimeoutException with a break; SocketTimeoutException添加一个单独的catch块,并带有一个break; inside it. 在里面。 Never just ignore an IOException. 永远不要忽略IOException. In this case I would say you should exit the loop on any IOException, so you could also consider putting the try/catch outside the loop. 在这种情况下,我会说您应该在任何IOException,上退出循环IOException,因此您也可以考虑将try / catch放在循环之外。

Reading one byte at a time is pretty poor. 一次读取一个字节非常糟糕。 I don't see the point of that. 我不明白这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM