How to keep TCP connection alive ? 如何保持 TCP 连接一直存活
代码
while ((modifiedSentence = inFromServer.readLine()) != null) {
System.out.println("FROM SERVER: " + modifiedSentence);
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
}
Note that in networking, connections can be lost at any time for a myriad of reasons (连接任何情况下因为任何原因都有可能断掉). If the connection traverses a NAT router, the entry in the NAT table could expire (when the connection is idle (当连接空闲的时候)) and the connection is lost due to that. The client could cease to function, or be suspended (especially laptops and mobile devices), or a cable could be disconnected, or WiFi (or cellular) signal could be interferred with, or ... the list can go on. Your server needs to be written to cope gracefully with loss of connection.