1

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?

1

1 Answer 1

2

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().

Sign up to request clarification or add additional context in comments.

2 Comments

So I think I should only be handling 'close' event, right?
Handle close too like I mentioned, otherwise you will get uncaught exceptions when error (e.g. ECONNRESET) is emitted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.