Question

This is making me a little nutty. I have the following running on an Android device:

SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
SSLSocketFactory sslsocketfactory = (SSLSocketFactory) sc.getSocketFactory();

Socket s = (SSLSocket) sslsocketfactory.createSocket(someHost, somePort);

OutputStream o = s.getOutputStream();

I have observed if the wireless connection is turned off the line:

OutputStream o = s.getOutputStream();

blocks indefinitely.

Which is AWESOME!!!! I can establish a timeout and if its exceeded I can assume there is some communication problem.

Except I can't find any confirmation that Socket.getOutputStream() is supposed to block.
Not in Oracle's javadoc nor in Google's Android javadoc.

Is this a JVM dependent kind of thing? I ran across the behavior using Android's dalvik jvm.

Has anyone experienced anything like this?

Mark

editing to add comment:

i'm intrigued by "SSLSocket.getOutputStream() initiates the SSL handshake if neceessary"

what defines "if necessary"? is this behavior (initiating the SSL handshake) something that's required by the JVM specification? IOW is it guaranteed across JVMs?

i ran across this behavior when i turned off my wifi connex and tried to create a socket to communicate with my server. the socket creation works fine and i've read about why. i've also read the only way to determine if a socket connex will work is to read/write data with it. this is not an option for me and i'm wondering if i can rely on getOutputStream() not returning within a minute or so as an indication that there is a connectivity problem.

thoughts? comments?

Was it helpful?

Solution

SSLSocket.getOutputStream() initiates the SSL handshake if neceessary, which involves reads, which may block. You should set a read timeout on the socket before calling it, with Socket.setSoTimeout().

I'm intrigued by "SSLSocket.getOutputStream() initiates the SSL handshake if neceessary"

what defines "if necessary"?

If it hasn't already been done, or the current SSL Session has been invalidated.

Is this behavior (initiating the SSL handshake) something that's required by the JVM specification? IOW is it guaranteed across JVMs?

No, it's required by the TLS/SSL specification.

I've also read the only way to determine if a socket connex will work is to read/write data with it. This is not an option for me.

Yes it is. You're doing it. The SSL handshake consists of reads and writes.

and I'm wondering if I can rely on getOutputStream() not returning within a minute or so as an indication that there is a connectivity problem.

You can rely on SocketTimeoutException being thrown during the handshake as an indication that the connection isn't working, provided you set a reasonable timeout with Socket.setSoTimeout() as I mentioned in my answer. A minute is reasonable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top