I'm using a Java socket client. In a case where the server is still connected to my client but it does not send a response to my message - I eventually get a read time out exception.
In that case I want to test to see if I should reconnect my socket or just keep it an re-use it.
I use this condition:
if (!socket.isConnected() || socket.isClosed() || !socket.isBound()) {
try {
socket.close();
} catch (IOException e1) {
}
// Wait on a new connection
socket = connectSocket(.....);
}
But I always seem to reconnect. When I log the values of the Boolean properties I see this:
connected: true closed: true bound: true
How can it be connected and closed?
TIA
This thread has some useful discussions on this topic. It turns out that
Socket.isConnected
returns true if it has (ever) been successfully connected.From the above thread:
The docs says:
and not as one perhaps would expect "returns true if the socket is connected to a server".
The behavior can be confirmed by looking at the source of Socket:
You could also run this little test snippet:
Which prints:
I must say that the documentation is quite unclear on this point, and that the method-name is a bit misleading.