Java socket reading error exception vs return code

1k views Asked by At

I am reading data off a socket using the following loop

InputStream in = getInputStream();
int retCode;

try {
  while( ( retCode = in.read()) > -1) {
    // do something
  }
  logger.info( "Done reading : Code " + retCode);
} catch( IOException ioe) {
  logger.warning( "IOException while reading : " + ioe.getMessage());
}

Sometimes connection gets dropped, which is expected, but the consequence is inconsistent.
I get an exception, or retCode==-1

Hence my question What determines exception vs return Code when reading a socket?

2

There are 2 answers

0
TheWhiteRabbit On BEST ANSWER

As @PeterLawrey rightly mentioned

if in.read() returns -1 - means the end of the stream is reached.

Exception in case on any unavailability of Stream / communication failure - depends on the Type of Exception thrown.

More

0
claude On

@PeterLawrey's answer is correct

if in.read() returns -1 - means the end of the stream is reached.

but there is more to it. The Java stream is backed by an operating system socket. If your program tries to write to the socket after the socket has been closed, or if it tries to read from a broken socket, then your program would get a SocketException with a reason such as broken pipe or connection reset by peer. I couldn't find anything official in the Java documentation, but it seems that if your program is blocked doing a read on the input stream of the socket, and the socket is then closed cleanly (without socket exception), then your program would be unblocked, and the read method would return -1.