tags:

views:

39

answers:

3

Hi, I have a SSLSocket pool and I need to check if the socket connection is sane before borrowing the object.

The isConnected, isInputShutdown and isOutputShutdown are useless because they don't check if both sides are connected and if I try to write or read from the socket I might get a SocketException.

Here is my code for testing a connection:

        if(sslSocket.isConnected() && 
               !sslSocket.isInputShutdown() && 
               !sslSocket.isOutputShutdown()){
            valid = true;
        }

This code doesn't work, as explained above.

So, what is the best way to check if a SSLSocket (or a regular Socket) is sane?

Thank you.

A: 

Would trying to read from the socket and catching a SocketException not be sane enough?

I can't read from the socket if there is nothing on the socket, that would be blocking. Checking if there is something available on the socket using the available() method from the inputStream is not enough also.
Isac
available() always returns zero for an SSLSocket, but there is the timeout mechanism, see my answer.
EJP
+1  A: 

If by "sane" you mean connected, you can only detect that a TCP socket is disconnected once you've tried to write to it:

http://lkml.indiana.edu/hypermail/linux/kernel/0106.1/1154.html

Hence, you need to make use of the exception accordingly in Java.

Bruno
I've tested sending a byte over the connection and catching the exception but it seems that this doesn't test the read operation and I can get an exception while reading later on. I might be wrong on this, will do more tests.
Isac
Same thing, you can't test whether you can read until you read. Between the time you test whether the socket is open and the time you read from it, the remote party may have closed the connection. It may even close it while you're reading.
Bruno
Remember, the state of the socket is controlled partially by the peer. So any check you perform on the local machine is vulnerable to becoming stale nearly immediately.
Darron
A: 

If reading, set a readTimeout via Socket.setSoTimeout() and catch SocketTimeoutException, or write and catch an IOException: connection reset. There are no other mechanisms. The isXXX() APIs you mention only tell you what you have done to this Socket. They don't tell you anything about the state of the connection.

EJP