Android socket connection timeout

After googling a lot I found out a solution to this problem. Add timeout to the socket connection.

mSocket.setSoTimeout(10*1000);

If there isn't any response, after 10 seconds it will throw SocketTimeoutException and in the catch of this exception close the connection if exists, then connect again.

catch (SocketTimeoutException e) {
  if (mSocket.isConnected()) {
    disconnect();
  }
  connect();
}

This is a simple example that shows how to set the timeout on a java socket :

sockAdr = new InetSocketAddress(SERVER_HOSTNAME, SERVER_PORT);
socket = new Socket();
timeout = 5000;
socket.connect(sockAdr, timeout);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream());
while ((data = reader.readLine())!=null) 
      log.e(TAG, "received -> " + data);
log.e(TAG, "Socket closed !");