为什么在Node.js中尝试重新连接我的TCP连接后出现ECONNREFUSED错误?

我正在尝试使用以下命令在Node.js中打开另一个程序的TCP连接:

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 }); 

如果其他程序没有运行(因此没有监听)连接错误是第一次正确处理,但如果我尝试再次连接(失败)超时后出现以下错误:

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

现在有没有人为什么不成功的连接第一次正确处理,但不是第二次? 我想继续尝试连接,而等待另一个程序启动。

每次重试都必须绑定到'error'事件 ,因为每次调用net.connect()返回一个新的net.Socket并带有自己的事件绑定:

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

要连续重试,请将“setup”包装在可根据需要调用的函数中:

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

@Jonathan Lonowski,当我使用我们的代码我注意到,在服务器重新启动它会打开多个连接。 “错误”事件发生在套接字closures之前。 将recursion调用移动到套接字closures事件正常工作。

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