trying to read from the InputStream, which throws an IOException
That is not correct. If the peer closes the socket:
read()
returns -1
readLine()
returns null
readXXX()
throws EOFException
, for any other X.
As InputStream
only has read()
methods, it only returns -1: it doesn't throw an IOException
at EOS.
Contrary to other answers here, there is no TCP API or Socket method that will tell you whether the peer has closed the connection. You have to try a read or a write.
You should use a read timeout.
InputStream.available()
doesn't solve the problem because it doesn't return an EOS indication of any kind. There are few correct uses of it, and this isn't one of them.