SSL connection timeout

How to set connection timeout for SSL sockets in Java?

For simple sockets, I can simply create a new instance of the socket without any endpoint using new Socket() , and then call connect (endpoint SocketAddress, int timeout) . With SSL sockets, I canโ€™t create the new SSLSocket() method and SSLSocketFactory.getDefault().createSocket() without any UnsupportedOperationException endpoint proxies with the message Unconnected sockets not implemented .

Is there a way to use connection timeouts for SSL sockets in Java using only standard java libraries?

+7
source share
3 answers

I believe that you can use your current approach to creating a Socket and then plug it in. To set SSL over the connection, you can use SSLSocketFactory.createSocket

Returns a socket located on top of an existing socket connected to the named host on this port.

This way you get full control over the connection, and then you will support SSL configuration on top of it. Please let me know if I misread your question.

+6
source

As of java 1.7, the following does not throw the exception indicated 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(); 

therefore it works as usual.

+3
source

While developing @predi's answer, I found that I also need to use setSoTimeout. Otherwise, sometimes he gets stuck in a handshake (with 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);' 
0
source

Source: https://habr.com/ru/post/886232/


All Articles