简体   繁体   English

尝试重新连接Node.js中的TCP连接后,为什么会收到ECONNREFUSED错误?

[英]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: 我正在尝试使用以下命令在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
});

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 to net.connect() returns a new net.Socket with its own event bindings: 您必须在每次重试时都绑定到'error'事件 ,因为对net.connect()每次调用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
// ...

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

@Jonathan Lonowski, while I was using ur code I noticed that on server restart it would open multiple connections. @Jonathan Lonowski,当我使用您的代码时,我注意到在服务器重启时它将打开多个连接。 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM