How to detect if net.Socket connection dies - node.js

Here's an interesting read: https://blog.stephencleary.com/2009/05/detection-of-half-open-dropped.html

Note in particular this remark:

It is important to note that the act of receiving data is completely passive in TCP; a socket that only reads cannot detect a dropped connection.

This is exactly what's happening in your case: your socket is waiting for new data to arrive, which never happens. Some OS'es, in particular of the UNIX type, may wait a very long time before they start invalidating open connections if a network interface went down.

The article also proposes a solution that may work on Node.js: enabling TCP Keepalive. This will periodically send packets to the peer to check if the connection is still working.

To enable this on your sockets:

socket.setKeepalive(true, 5000);

This will start checking the connection 5 seconds after it has received the last packet. More info here: https://nodejs.org/api/net.html#net_socket_setkeepalive_enable_initialdelay


I had the same issue. I ended up doing this as a fix:

const _connect = () => {
  const socket = new net.Socket();
    socket.connect(this.port, this.host);
    socket.setTimeout(10000);

    socket.on('timeout', () => {
        socket.destroy();
        _connect(); 
    });
}