【发布时间】:2011-06-11 20:13:25
【问题描述】:
我正在开发一个使用 SSLSocket 连接到服务器的 Android 应用程序。这是我正在使用的代码:
// Connect
if (socket == null || socket.isClosed() || !socket.isConnected()) {
if (socket != null && !socket.isClosed())
socket.close();
Log.i(getClass().toString(), "Connecting...");
if (sslContext == null) {
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new SecureRandom());
}
SSLSocketFactory socketFactory = sslContext.getSocketFactory();
socket = (SSLSocket)socketFactory.createSocket(host, port);
socket.setSoTimeout(20000);
socket.setUseClientMode(true);
connected = true;
Log.i(getClass().toString(), "Connected.");
}
// Secure
if (connected) {
Log.i(getClass().toString(), "Securing...");
SSLSession session = socket.getSession();
secured = session.isValid();
if (secured) {
Log.i(getClass().toString(), "Secured.");
}
else
Log.i(getClass().toString(), "Securing failed.");
}
问题是在下面一行中进行 TLS 握手大约需要 5 秒或更多时间:
SSLSession session = socket.getSession();
我做了一个类似的 iPhone 应用程序,握手只需要 1 秒,所以我认为问题不在于我正在连接的服务器,它可能在上面的代码中。连接本身已经足够快了,只是 TLS 握手很慢。
有谁知道在Android中是否正常,如果不正常,如何使其更快?
谢谢。
21.01.11 编辑:
我发现,当我连接到另一台服务器时,握手速度很快,例如 paypal.com:443。
但我之前一直连接到另一台服务器 - 我编写的 .NET 服务。正如我之前所说,我不认为问题出在那个服务器上,因为如果我用我的 iPhone 应用程序连接到它,握手会很快。现在我不知道为什么它在 iPhone 上快而在 Android 上慢。建立连接后,我在.NET服务器中唯一要做的就是:
Console.WriteLine("New client connected.");
this.sslStream = new SslStream(tcpClient.GetStream(), true);
this.sslStream.ReadTimeout = 15000;
this.sslStream.WriteTimeout = 15000;
Console.WriteLine("Beginning TLS handshake...");
this.sslStream.AuthenticateAsServer(connection.ServerCertificate, false, SslProtocols.Tls, false);
Console.WriteLine("TLS handshake completed.");
【问题讨论】: