Mike Heffelfinger
Mike Heffelfinger

Reputation: 415

Why do I get a ECONNREFUSED error after trying to reconnect my TCP connection in Node.js?

I'm trying to open a TCP connection in Node.js to another program using the following command:

connection = net.connect(18003, function() {
});

connection.on('close', function() {
  console.log('Connection closed');
});
connection.on('error', function() {
  console.log('Connection error');

  setTimeout(function () {
    connection = net.connect(18003, ipAddress,
      function() {
    });
  }, 10000); //Try to reconnect
});

If the other program's not running (therefor not listening) the connection error is handled correctly the first time, but if I try to connect again (unsuccessfully) after a timeout I get the following error:

events.js:68
  throw arguments[1]; // Unhandled 'error' event

Error: connect ECONNREFUSED

Does anyone now why the unsuccessful connect is handled correctly the first time but not the second? I'd like to keep trying the connection while waiting on the other program to start.

Upvotes: 1

Views: 4838

Answers (2)

limplash
limplash

Reputation: 81

@Jonathan Lonowski, while I was using ur code I noticed that on server restart it would open multiple connections. the 'error' event occurs before the closing of socket. moving the recursive call to socket close event works correctly.

function setupConnection() {
  connection = net.connect(18003, ipAddress, function () {
  });
  connection.on('close', function() {
    console.log('Connection closed');
    setTimeout(setupConnection, 10000); //Try to reconnect EDITED
  });

  connection.on('error', function() {
    console.log('Connection error');
  });
}
setupConnection();

Upvotes: 0

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123473

You'll have to bind to the 'error' event with each retry as each call to net.connect() returns a new net.Socket with its own event bindings:

// ...
  setTimeout(function () {
    connection = net.connect(18003, ipAddress,
      function() {
    });

    connection.on('error', function () {
      console.log('Connection retry error');
    });
  }, 10000); //Try to reconnect
// ...

For continuously retrying, wrap the "setup" in a function that can be called as needed:

function setupConnection() {
  connection = net.connect(18003, ipAddress, function () {
  });

  connection.on('close', function() {
    console.log('Connection closed');
  });

  connection.on('error', function() {
    console.log('Connection error');

    setTimeout(setupConnection, 10000); //Try to reconnect
  });
}

setupConnection();

Upvotes: 5

Related Questions