SSL 套接字连接超时
如何在 Java 中配置 SSL 套接字的连接超时?
对于普通套接字,我可以使用 new Socket()
创建没有任何目标端点的新套接字实例,然后调用 connect(SocketAddress 端点, int timeout) 方法。使用 SSL 套接字,我无法创建没有端点的 new SSLSocket()
和 SSLSocketFactory.getDefault().createSocket()
方法,并会抛出 UnsupportedOperationException
和 < strong>未连接的套接字未实现消息。
有没有办法在 Java 中使用 SSL 套接字的连接超时,仅使用标准 java 库?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我相信您可以使用当前创建 Socket 然后连接它的方法。要通过连接建立
SSL
,您可以使用SSLSocketFactory.createSocket
这样您就可以完全控制连接,然后您可以在其上协商设置 SSL。如果我误读了你的问题,请告诉我。
I believe you could use your current approach of creating the
Socket
and then connecting it. To establishSSL
over the connection you could useSSLSocketFactory.createSocket
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.
对于 java 1.7,以下内容不会引发问题中所述的异常:
因此一切照常。
With java 1.7 the following does not throw the exception stated in the question:
so it's business as usual.
详细说明@predi的答案,我发现我也需要使用“setSoTimeout”。否则有时它会卡在握手中(在非常不稳定的连接上):
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):