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 lib开发者_JAVA百科s 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);`
精彩评论