There is no TCP API that will tell you the current state of the connection. isConnected()
and isClosed()
tell you the current state of your socket. Not the same thing.
-
isConnected()
tells you whether you have connected this socket. You have, so it returns true. -
isClosed()
tells you whether you have closed this socket. Until you have, it returns false. -
If the peer has closed the connection in an orderly way
read()
returns -1readLine()
returnsnull
-
readXXX()
throwsEOFException
for any other XXX. -
A write will throw an
IOException
: ‘connection reset by peer’, eventually, subject to buffering delays.
-
If the connection has dropped for any other reason, a write will throw an
IOException
, eventually, as above, and a read may do the same thing. -
If the peer is still connected but not using the connection, a read timeout can be used.
-
Contrary to what you may read elsewhere,
ClosedChannelException
doesn’t tell you this. [Neither doesSocketException: socket closed.
] It only tells you that you closed the channel, and then continued to use it. In other words, a programming error on your part. It does not indicate a closed connection. -
As a result of some experiments with Java 7 on Windows XP it also appears that if:
- you’re selecting on
OP_READ
select()
returns a value of greater than zero- the associated
SelectionKey
is already invalid (key.isValid() == false
)
it means the peer has reset the connection. However this may be peculiar to either the JRE version or platform.
- you’re selecting on