I want to have a SSL encrypted TCP server on the android device and a client on the computer which will connect to the device.
I create a SSLServerSocket on the Android device with an own keystore.
final KeyStore localTrustStore = KeyStore.getInstance("BKS"); //NON-NLS final InputStream in = context.getResources().openRawResource(R.raw.syncapp); localTrustStore.load(in, "secret".toCharArray()); //Keystore pw in.close(); final SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); //NON-NLS final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(localTrustStore); final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(localTrustStore, "secret".toCharArray()); //privat key pw sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); serverSocket = sslContext.getServerSocketFactory().createServerSocket(SERVER_PORT); ((SSLServerSocket) serverSocket).setNeedClientAuth(true);
Then I wait for a client to connect. When a client wants to connect a new thread is started and the streams get demanded:
final DataInputStream input = new DataInputStream(this.clientSocket.getInputStream()); final DataOutputStream output = new DataOutputStream(new BufferedOutputStream(clientSocket.getOutputStream()));
First I used this code with USB-Tethering to gain a connection between the computer and the android device. So no Wifi/Network was enabled. Everything worked perfectly.
Then I activated the wifi on the android device and connect to a wlan without internet.
But now the call to getInputStream() seems to take 5 to 10 seconds.
If I deactivate SSL it works perfectly.
If the wlan does connect to the internet there is no delay as well.
I tested this with Android 4.2 and 5.1.
Update: Now I could test this issue with Android 6. And the issue seems to be fixed there…
The Handshake is finished correctly but after that there seems to be some sort of delay on the android device. (The call to getInputStream consumes that time)
Some devs are saying that it will do a DNS reverse lookup which will run into a timeout.
Take a look at the capture, the first connection was made while wifi was disabled. It took 0.3 sec to make the data transfer. Then I just activated the wifi, I didn’t connect over the wifi, it still communicates over usb. And it took over 5 sec.
I found the issue here as well, but they are using a client socket. I need a server socket. Does anyone have any idea how to fix this issue?
You are right that there is a reverse DNS lookup that is timing out. In certain Java Runtime Environments, during the handshake with a raw IP address, the SSLContext unnecessarily performs a lookup of the server’s IP address. This is to determine if the common name of the server certificate matches. Try using one of the solutions mentioned here: