bodacydo
bodacydo

Reputation: 79329

How do I make a node.js TCP connection reconnect automatically?

I wrote a TCP client and server in node.js. I can't figure out how to make client reconnect when it disconnects for any reason whatsoever. I understand I have to handle 'close' event, but it's an event that gets fired only when connection gracefully closes. I don't know how to handle network errors when connection just ends because of network issues.

Here's the code that I've so far:

function connect () {
  client = new net.Socket();
  client.connect(config.port, config.host, function () {
    console.log('connected to server');
  });

  client.on('close', function () {
    console.log('dis-connected from server');
    connect();
  });

  client.on('error', ...); // what do I do with this?
  client.on('timeout', ...); // what is this event? I don't understand
}

Can anyone explain what do I do in error and timeout case? And how do I know that the network has disconnected and reconnect?

Upvotes: 1

Views: 4103

Answers (1)

mscdex
mscdex

Reputation: 106696

You can probably just leave the error event handler as a no-op/empty function, unless you want to also log the error or something useful. The close event for TCP sockets is always emitted, even after error, so that is why you can ignore it.

Also, close event handlers are passed a boolean had_error argument that indicates whether the socket close was due to error and not a normal connection teardown.

The timeout event is for detecting a loss of traffic between the two endpoints (the timeout used is set with socket.setTimeout().

Upvotes: 2

Related Questions