简体   繁体   中英

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(..)

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

  2. It is non-zero, so you're getting a SocketTimeoutException inside your loop, and ignoring it, so you spin forever. Add a separate catch block for SocketTimeoutException with a break; inside it. Never just ignore an 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.

Reading one byte at a time is pretty poor. I don't see the point of that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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