0

can anyone tell me, why I won't get an Exception, if remote socket is closing and sending FIN + ACK? Wireshark tells me, that FIN + ACK is received and ACK is sent by OS.

Here is my code. I really tried everything.

byte firstByte = (byte)instream.read();
if (firstByte == -1){
    return null;
}
byte[] bytes = new byte[instream.available() + 1];
bytes[0] = firstByte;
instream.read(bytes, 1, bytes.length - 1);

instream is of Socket.getInputStream(), outstream of Socket.getOutputStream().

Connection will be closed by my 15 sec heartbeats.

  • Socket is closed from the other side and your next operation to read from the socket from this side will just tell you that there is nothing to read from like end of file. But if you close the socket from your side and perform this operation it will give you exception like reading from a closed file. You are using InputStream and as such it hides whats underneath (file or socket) and act the same way for both – ata Jan 23 '15 at 15:56

1 Answers1

0

It is not a system-level error for the remote machine to close a network connection. Attempting to read from the InputStream associated with the Socket representing the local end of a closed connection will detect an end-of-file condition, which is a natural possibility for any Inputstream.

Per its docs, InputStream.read() returns -1 when the end of the file has been reached. For the InputStream of a network socket, this is a fairly reliable indication that the connection has been closed.

What you need to watch out for is the remote client dropping the connection without closing it cleanly. The local machine cannot detect that, and an attempt to read from the local socket of such a connection will block indefinitely.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157