Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create SSLSocket by SSLSocketFactory with set connection timeout

My code is here:

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, getAllCerts(), new SecureRandom());
SSLSocketFactory factory = sslContext.getSocketFactory();
mSocket = (SSLSocket) factory.createSocket("myhost.com", socketPort[index]);

I have to check table of ports and choose the open one. Everything works ok, but on createSocket() my application loose a lot of time. If I have 5 ports and the last is open connecting takes about 3 minutes.

How can I set timeout on SSLSocketFactory to speed up connection?

like image 604
Chris Avatar asked Aug 31 '11 08:08

Chris


2 Answers

In case you are still wondering, you can use the idea given in https://groups.google.com/forum/#!topic/android-developers/EYtMO5WoXXI

import javax.net.ssl.SSLSocketFactory;

// Create a socket without connecting
SSLSocketFactory socketFactory = SSLSocketFactory.getDefault();
Socket socket = socketFactory.createSocket();

// Connect, with an explicit timeout value
socket.connect(new InetSocketAddress(endpoint.mServer,
endpoint.mPort), CONNECT_TIMEOUT);
like image 105
Shervin Avatar answered Oct 16 '22 10:10

Shervin


Try wrapping an existing socket instead:

Socket socketConn = new Socket();
socketConn.connect(addr, DEFAULT_CONNECT_TIMEOUT);
mSocket = socketConn.getSocketFactory().createSocket(socketConn, hostname, port, true);
like image 25
Jim Cortez Avatar answered Oct 16 '22 10:10

Jim Cortez