java SSL 套接字连接超时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5715751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SSL Socket connect timeout
提问by Peter ?tibrany
How can I configure connect timeout for SSL Sockets in Java?
如何在 Java 中为 SSL 套接字配置连接超时?
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 implementedmessage.
对于普通套接字,我可以简单地创建没有任何目标端点的新套接字实例new Socket()
,然后调用connect(SocketAddress endpoint, int timeout)方法。使用SSL套接字,我不能创建new SSLSocket()
和SSLSocketFactory.getDefault().createSocket()
方法,没有终点抛出UnsupportedOperationException
与未连接的插座不落实的消息。
Is there a way to use connect timeouts for SSL Sockets in Java, using standard java libs only?
有没有办法在 Java 中使用 SSL 套接字的连接超时,只使用标准的 Java 库?
采纳答案by cnicutar
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
我相信您可以使用当前的方法来创建Socket
然后连接它。要建立SSL
您可以使用的连接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 thenyou negociate setting up SSL on top of it. Please let me know if I misread your question.
通过这种方式,您可以完全控制连接,然后在其上协商设置 SSL。如果我误读了您的问题,请告诉我。
回答by predi
With java 1.7 the following does not throw the exception stated in the question:
使用 java 1.7,以下不会抛出问题中所述的异常:
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.
所以一切照旧。
回答by Gibezynu Nu
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):
详细说明@predi 的回答,我发现我也需要使用“setSoTimeout”。否则有时它会卡在握手中(在非常不稳定的连接上):
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);`