我的代码假设与某个对等方启动 SSL 套接字,提取证书并关闭套接字。问题是,createSocket()似乎阻塞了很长时间。如何设置合理的超时时间?这是我的完整代码:public static void main(String[] args) throws Exception { SSLContext sslCtx; sslCtx = SSLContext.getInstance("TLSv1.2"); sslCtx.init(null, new TrustManager[]{new X509TrustManager() { private X509Certificate[] accepted; @Override public void checkClientTrusted(X509Certificate[] xcs, String string) { } @Override public void checkServerTrusted(X509Certificate[] xcs, String string) { accepted = xcs; } @Override public X509Certificate[] getAcceptedIssuers() { return accepted; } }}, null); System.out.println("start ...."); try (SSLSocket sslSocket = (SSLSocket) sslCtx.getSocketFactory().createSocket("156.70.54.68", 443)) { sslSocket.setSoTimeout(5_000); Certificate[] certificates = sslSocket.getSession().getPeerCertificates(); System.out.println(certificates.length); } catch (Exception e) { System.out.println(e); } }
1 回答
慕神8447489
TA贡献1780条经验 获得超1个赞
不要先调用socket(String, int),然后调用socket(),然后定义超时,然后调用connect(InetSocketAddress, int),它采用 int 作为超时值。
try (SSLSocket sslSocket = (SSLSocket) sslCtx.getSocketFactory().createSocket()) {
sslSocket.setSoTimeout(5_000);
Certificate[] certificates = sslSocket.getSession().getPeerCertificates();
System.out.println(certificates.length);
sslSocket.connect(new InetSocketAddress("156.70.54.68", 443), 5_000);
} catch (Exception e) {
System.out.println(e);
}
添加回答
举报
0/150
提交
取消