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?
The handshake timeout specifies the duration in time that the system tries to establish an SSL connection before halting the operation. New Behavior. Beginning in BIG-IP 11.2. 0, the default SSL handshake timeout is 10 seconds and can be configured by users.
You can make an instance of a socket object and call a gettimeout() method to get the default timeout value and the settimeout() method to set a specific timeout value. This is very useful in developing custom server applications.
Re: Recommended Value for http socket timeout Given that on Policy server the default idle timeout for socket is 10min, I think 10 min is good vlaue for it.
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);`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With