socketsnetwork-programmingtcpniokeep-alive

How SO_KEEPALIVE works in socket programming


I'm a newbie to networks, please guide me for the following.

As per my understanding, by default in the OS Level, the client sends the keep-alived probes to the server and it checks if the connection is active, else it closes the connection.

But in the socket programming in the server side implementation, if I enable keep-alived how it works, is the check done from the server side to client?

Code snippet:

ServerSocketChannel scChannel = ServerSocketChannel.open();
scChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, true);

I am working on java NIO (non-blocking), how this mechanism works here?


Solution

  • by default in the OS Level, the client sends the keep-alived probes to the server and it checks if the connection is active, else it closes the connection.

    TCP keep-alives are NOT enabled by default. You have to enable them explicitly on a per-socket basis.

    But in the socket programming in the server side implementation, if I enable keep-alived how it works, is the check done from the server side to client?

    TCP is bi-directional, so keep-alive probes work the exact same way from the server to the client, as they do from the client to the server. Either peer can enable keep-alives for itself independently of the other peer. Probes are handled at the TCP level, not at the application level, so you don't need to do anything to send/handle them, and they won't interfere with any application data being sent back and forth.

    As for how the probes themselves work - when keep-alives are enabled on a given socket, it starts a couple of internal timers. The first timer resets whenever data is received. If that timer elapses, the socket sends a 0-length packet to the peer and expects an ACK in reply. If no ACK is received before the second timer elapses, another 0-length packet is sent, repeating until an ACK is received or the max number of probes has been reached. If the latter happens, the socket considers the connection to be dead. The application will then have to detect that condition (via read/write failures, or close/reset notifications, etc) so it can close the socket.