我有这个简单的服务器,它接受来自客户端的 TCP 套接字连接。TCPConnectionHandler
每个尝试连接的客户端都会使用新的 Socket获得自己的实例。我不明白我应该如何处理客户端断开连接。这是我的TCPConnectionHandler
:
@Override
public void run() {
try {
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String line;
while (!(line = br.readLine()).isEmpty()) {
Message messageObj = Tools.JSON2Message(line);
messageObj.setSourceIP(socket.getInetAddress().toString().substring(1));
logger.info("TCPCH: Message received from: " + messageObj.getSourceIP() + ". Type of message: " + messageObj.getClass().getSimpleName());
Message response;
if (messageObj instanceof HandshakeReq) {
response = new HandshakeHandler(requestRouter.getTabletCollection()).handleRequest((HandshakeReq) messageObj, this);
} else {
response = requestRouter.routeAndHandleRequest(messageObj);
}
if (response != null)
sendMessageTCP(response);
}
} catch (IOException e) {
logger.error("TCPConnectionHandler failed: " + e.getCause());
e.printStackTrace();
}
}
现在,当客户端断开连接时,我会NullPointerException
将该跟踪追溯到该run()
方法。在开始时,我认为它是InputStream
从当客户端断开连接时Socket
变成的对象获得的,而我在调用时得到。我无法捕捉到这个异常。当客户端断开连接时实际会发生什么,我应该如何正确地捕捉到与上述片段相关的情况? null
NullPointerException
BufferedReader
readLine()