0
我有這個接受來自客戶端的TCP套接字連接的簡單服務器。每個嘗試連接的客戶端都使用新的Socket獲取自己的實例TCPConnectionHandler
。我不明白我應該如何處理客戶端斷開連接。這裏是我的TCPConnectionHandler
:處理TCP客戶端斷開連接
@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
,當BufferedReader
調用readLine()
時,我得到NullPointerException
。儘管如此,我無法理解這個例外。客戶斷開連接時究竟發生了什麼,我應該如何正確捕獲與上述代碼段有關的內容?
你在哪裏有NullPointerException?或者只是給堆棧跟蹤 –