Search code examples
javascriptnode.jssocketserror-handlingtcp

Node.js tcp socket shut off trigger


I use node.js with the NET class to connect multiple Rasperry Pi's.

//Server
const net = require('node:net');
const server = net.createServer();

//Client
const tcpConnect = net.createConnection(SERVERINFO);

Thereby I can easily register multiple clients, open/close streams. Everything works without any problems.

But now I noticed that the callbacks.

tcpConnect.on('end', () => { console.log('end triggered') });
tcpConnect.on('close', () => { console.log('close triggered') });
tcpConnect.on('error', () => { console.log('error triggered') });

do not work if the server suddenly has a power failure (e.g. power supply is pulled). The clients don't trigger an error/end or close, so I can't close the connection properly. As a result, an error is not triggered until the next attempt to write something to an existing stream. But this is not an option for me, especially for "online monitoring".

Does anyone know a way to identify the shut off of the server immediately?


Solution

  • You need to enable TCP keep-alives in order for the client to detect that the server is no longer responding and you can tune how often it checks on an idle connection. (I've written a language generic description at the beginning of this answer.)

    In node it appears you can do this: socket.setKeepAlive(true), i.e. for this client to detect the server is gone when the socket is idle:

    //Client
    const tcpConnect = net.createConnection(SERVERINFO);
    tcpConnect.setKeepAlive(true);