Azamat Abdullaev
Azamat Abdullaev

Reputation: 806

Correct way of reconnecting to the socket after ECONNRESET (Nodejs net.Socket)

I am using the native Nodejs net module for establishing socket connection to a hardware device over LAN. I have implemented some event handlers, for example, I am listening to data event, and everything works as expected!

const net = require('net');
let reader = new net.Socket();

reader.connect(READER_PORT, READER_IP);

// Some event handlers, working perfectly fine...
reader.on('data', (data) => {
    // Process the data           
});

reader.on('close', (error) => {
   // Reconnect here
});

However, when I am not using the connection for about 5-10 minutes (it staying idle), it is automatically closing itself, and it is emitting the close event with the following error:

read ECONNRESET
    at TCP.onStreamRead (internal/stream_base_commons.js:208:20) {
  errno: 'ECONNRESET',
  code: 'ECONNRESET',
  syscall: 'read'
}

I want to re-establish the connection when I am getting the close or error event. I have tried to use the reader.connect() as I initially did above when I caught those events. However, I am not receiving any data from the socket after this, i.e. data handlers are never called.

What is the correct way of reconnecting to the socket in this case?

Upvotes: 3

Views: 2244

Answers (1)

Azamat Abdullaev
Azamat Abdullaev

Reputation: 806

As it was mentioned by @Lawrence Cherone, sockets close after some period of time if idle. To solve this, the TCP keep-alive needs to be enabled.

For Node.js (the net module) it can be enabled using socket.setKeepAlive() method (https://nodejs.org/api/net.html#net_socket_setkeepalive_enable_initialdelay). And it solved my problem.

UPDATE 2021

I have written everything in detail about it in my article: https://abdullaev.dev/how-to-integrate-nodejs-with-uhf-rfid-reader/

Upvotes: 1

Related Questions