In our product we are creating an SSLSocket to a server using an SSLSocketFactory.
When creating the socket to the server we are using one of two approaches depending on a product configuration:
(1) We create a standard socket then wrap it in an SSLSocket.
SSLSocketFactory factory = ...
Socket s = new Socket(host, port);
SSLSocket sslSocket = (SSLSocket)factory.createSocket(s, host, port, true);
(2) We simply create an SSL socket:
SSLSocketFactory factory = ...
Socket socket = factory.createSocket(host, port);
In our test environment both methods works equally well. However at different customer sites we found that in some cases one of the methods causes significant delay while the other connects immediately (each time a different method). This is not consistent and sometimes not reproducible.
Can anyone tell what is the theoretical difference between these connection methods and which one should be recommended under which circumstances ?
Significant delays in socket programming are almost always DNS delays. You need to be aware that Java does reverse DNS as well as forward DNS. Make sure you can resolve all relevant peer hostnames to IP addresses and vice versa at all hosts. The delay is incurred creating the Socket or the InetAddress it is to connect to, or both. If you do that separately you will see the delay there, before you call createSocket(socket, …); if you let the SSLSocketFactory create its own Socket by calling createSocket(host, port, …), the delay will occur at that point.