java 通过设置连接超时的 SSLSocketFactory 创建 SSLSocket

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7254389/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:18:33  来源:igfitidea点击:

Create SSLSocket by SSLSocketFactory with set connection timeout

javaandroidsocketstimeout

提问by Chris

My code is here:

我的代码在这里:

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, getAllCerts(), new SecureRandom());
SSLSocketFactory factory = sslContext.getSocketFactory();
mSocket = (SSLSocket) factory.createSocket("myhost.com", socketPort[index]);

I have to check table of ports and choose the open one. Everything works ok, but on createSocket() my application loose a lot of time. If I have 5 ports and the last is open connecting takes about 3 minutes.

我必须检查端口表并选择开放的。一切正常,但在 createSocket() 上,我的应用程序浪费了很多时间。如果我有 5 个端口,而最后一个端口是打开的,则连接大约需要 3 分钟。

How can I set timeout on SSLSocketFactory to speed up connection?

如何在 SSLSocketFactory 上设置超时以加快连接速度?

回答by Shervin

In case you are still wondering, you can use the idea given in https://groups.google.com/forum/#!topic/android-developers/EYtMO5WoXXI

如果您仍然想知道,您可以使用https://groups.google.com/forum/#!topic/android-developers/EYtMO5WoXXI 中给出的想法

import javax.net.ssl.SSLSocketFactory;

// Create a socket without connecting
SSLSocketFactory socketFactory = SSLSocketFactory.getDefault();
Socket socket = socketFactory.createSocket();

// Connect, with an explicit timeout value
socket.connect(new InetSocketAddress(endpoint.mServer,
endpoint.mPort), CONNECT_TIMEOUT);

回答by Jim Cortez

Try wrapping an existing socket instead:

尝试包装现有的套接字:

Socket socketConn = new Socket();
socketConn.connect(addr, DEFAULT_CONNECT_TIMEOUT);
mSocket = socketConn.getSocketFactory().createSocket(socketConn, hostname, port, true);