title: TLS connection using SSLSocket is slow in Android OS
body: <p>I'm developing an Android app which uses SSLSocket to connect to a server. This is the code I'm using:</p>
  
  <pre><code>// Connect
  if (socket == null || socket.isClosed() || !socket.isConnected()) {
      if (socket != null &amp;&amp; !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.");
  }
  </code></pre>
  
  <p>The problem is that it takes about 5 seconds or event more to do the TLS handshake in the line below:</p>
  
  <pre><code>SSLSession session = socket.getSession();
  </code></pre>
  
  <p>I have made a similar iPhone app, the handshake takes just 1 second there, so I think the problem is not in the server I'm connecting to, it's maybe in the code above. The connection itself is fast enough, just the TLS handshake is slow.</p>
  
  <p>Does anybody know if it's normal in Android, or if it is not, how to make it faster?</p>
  
  <p>Thank you.</p>
  
  <p><strong>EDITED on 21.01.11:</strong></p>
  
  <p>I have found out, that the handshake is fast when I connect to another server, for example <strong>paypal.com:443</strong>.</p>
  
  <p>But I had been connecting to another server before - a .NET service written by me. As I had said before, I did not think the problem was in that server because if I connect to it with my iPhone App the handshake is fast. Now I don't know why it is fast on iPhone and slow on Android. After the connection is established, the only thing I do in the .NET server is:</p>
  
  <pre><code>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.");
  </code></pre>