- Two computers are connected by socket connection. If the server/client closes the connection
from their end(i.e closes theInputStream,OutputStreamandSocket) then how can I inform
the other end about the disconnection? There is one way I know of – trying to read from theInputStream,
which throws anIOExceptionif connection is closed, but is there any other way to detect this? - Another question, I looked the problem up on the internet and saw
inputStream.available()
does not solve this problem. Why is that?
Additional Information : I’m asking for another way because my project becomes tough to handle if I have to try to read from the
InputStrem to detect a disconnection.
That is not correct. If the peer closes the socket:
read()returns -1readLine()returns nullreadXXX()throwsEOFException, for any other X.As
InputStreamonly hasread()methods, it only returns -1: it doesn’t throw anIOExceptionat 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.