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

Viewed 939

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?

1 Answers
Related