Booyaches
Booyaches

Reputation: 1719

Handling TCP client disconnections

I have this simple server that accepts TCP socket connections from clients. Each client that tries to connect, gets its own instance of TCPConnectionHandler with new Socket. I don't understand how should I handle client disconnections. Here is my 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();
    }

}

Now, when a client disconnects I get NullPointerException that traces back to the run()method. On the beggining I thought that it is InputStream obtained from Socket object that becomes null when a client disconnects and I get NullPointerException when BufferedReader calls readLine(). I was unable to catch this exception though. What actually happens when client disconnects and how should I correctly catch that in relation to the above snippet?

Upvotes: 0

Views: 894

Answers (1)

user207421
user207421

Reputation: 311039

Your loop condition is wrong. If a client disconnects, readLine() will return null, not an empty string. Your present loop will therefore throw a NullPointerException instead of exiting cleanly.

Additionally, just add more catch phase in try-block.

catch (NullPointerException ex) {
    socket.close() 
}

then everything will be okay.

Upvotes: 1

Related Questions