Chris
Chris

Reputation: 121

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?

Upvotes: 10

Views: 14250

Answers (2)

Jim Cortez
Jim Cortez

Reputation: 471

Try wrapping an existing socket instead:

Socket socketConn = new Socket();
socketConn.connect(addr, DEFAULT_CONNECT_TIMEOUT);
mSocket = socketConn.getSocketFactory().createSocket(socketConn, hostname, port, true);

Upvotes: 2

Shervin
Shervin

Reputation: 409

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);

Upvotes: 11

Related Questions