Android socket connection timeout

后端 未结 2 1788
無奈伤痛
無奈伤痛 2021-01-05 09:43

My android app is connected to the server through socket, which is coded in node.js. When the is left in the foreground for 15 minutes it losses connection to the server. Th

相关标签:
2条回答
  • 2021-01-05 09:51

    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();
    }
    
    0 讨论(0)
  • 2021-01-05 10:00

    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 !");
    
    0 讨论(0)
提交回复
热议问题