Isac
Isac

Reputation: 2068

How do I check if a SSLSocket connection is sane on Java?

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?

Upvotes: 2

Views: 3726

Answers (4)

Jared
Jared

Reputation: 109

I was having the same problem and here was the fix: Since the sslSocket is created from the sslServerSocket, closing the server socket instead of the socket will work.

Using the the suggested time out, catching the SSLException, and closing the socket should help to ensure the connection is still valid without the need for threading.

sslserversocket = (SSLServerSocket) sslserversocketfactory.createServerSocket(sslServerSocketPort);
sslsocket = (SSLSocket) sslserversocket.accept();
sslsocket.setSoTimeout(5000);

// Restart connections
if(sslserversocket.isClosed() || sslserversocket == null){
    sslserversocket.close();
    startSSLServer();
}

Upvotes: 0

user207421
user207421

Reputation: 310936

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.

Upvotes: 0

Bruno
Bruno

Reputation: 122659

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.

Upvotes: 3

user400348
user400348

Reputation: 236

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

Upvotes: 0

Related Questions