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.
You’ll have to bind to the
'error'event with each retry as each call tonet.connect()returns a newnet.Socketwith its own event bindings:For continuously retrying, wrap the “setup” in a function that can be called as needed: