Close TCP connection after a minute of inactivity

I have a server that creates a new thread (client handler) every time a client connects to it. I want the client handler to close the connection if it has not received a DataInputstream message from the client in a minute.

I have tried:

if (System.currentTimeMillis() > startTime + 60000) {
    System.out.println("Time up!!! for client: "+this.socket);
    dos.writeUTF("close");
    this.socket.close
    break;
}

However, this only gets to the if statement after the client sends a message and I want to close the connection after 1 minute of inactivity from the client automatically.

Answer

There’s multiple scenarios:

  1. The timeout after the last read should be 60 seconds: Simply set the read() timeout: socket.setSoTimeout(60*1000); So if the reading thread has not received any data for a minute, the read() request will fail. Handle that exception accordingly, and you’ve got it.
  2. The total connection timeout shall be 60 seconds, but the input still done in blockning mode: same as (1), but after each successful read you reduce the given timeout: socket.setSoTimeout(msLeft);
  3. The total connection timeout shall be 60 seconds, but the input can be done in non-blocking mode: This uses is very different from those classes you use in your example, but here is a good guide to that: Non-blocking sockets.

However, I would stick to blocking I/O if possible, it’s simply better for a lot of reasons.