简体   繁体   中英

SSL Socket connect timeout

How can I configure connect timeout for SSL Sockets in Java?

For plain sockets, I can simply create new socket instance without any target endpoint using new Socket() , and then call connect(SocketAddress endpoint, int timeout) method. With SSL sockets, I cannot create new SSLSocket() and SSLSocketFactory.getDefault().createSocket() method with no endpoint throws UnsupportedOperationException with Unconnected sockets not implemented message.

Is there a way to use connect timeouts for SSL Sockets in Java, using standard java libs only?

I believe you could use your current approach of creating the Socket and then connecting it. To establish SSL over the connection you could use SSLSocketFactory.createSocket

Returns a socket layered over an existing socket connected to the named host, at the given port.

This way you get full control over the connection and then you negociate setting up SSL on top of it. Please let me know if I misread your question.

With java 1.7 the following does not throw the exception stated in the question:

String host = "example.com";
int port = 12345;
int connectTimeout = 5000;
SSLSocket socket = (SSLSocket)SSLSocketFactory.getDefault().createSocket();
socket.connect(new InetSocketAddress(host, port), connectTimeout);
socket.startHandshake();

so it's business as usual.

Elaborating on @predi's answer, I found that I needed to use "setSoTimeout" too. Otherwise sometimes it gets stuck in the handshake (on very unstable connections):

    final int connectTimeout = 30 * 1000;
    SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
    socket.setSoTimeout(connectTimeout);
    socket.connect(new InetSocketAddress(hostAddress, port), connectTimeout);
    socket.startHandshake();
    socket.setSoTimeout(0);`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM