node.js 在不同主机上建立套接字连接时出现“ECONNREFUSED”错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7949277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:42:24  来源:igfitidea点击:

Getting 'ECONNREFUSED' error when socket connection is established on different host

node.js

提问by user482594

Apparently, I am testing out simple TCP server that uses Node.js.

显然,我正在测试使用 Node.js 的简单 TCP 服务器。

The server code, and the client code works well if they are both on the samemachine.

如果服务器代码和客户端代码在同一台机器上,则它们运行良好。

However, it seems that when I run the server on the different machine and test to connect to the server from the client in different machine, I get error like below.

但是,似乎当我在不同机器上运行服务器并测试从不同机器上的客户端连接到服务器时,出现如下错误。

Error: connect ECONNREFUSED
at errnoException (net.js:589:11)
at Object.afterConnect [as oncomplete] (net.js:580:18)

I tried by typing IP address of the server, or the domain name of the server, but no luck.

我尝试输入服务器的 IP 地址或服务器的域名,但没有成功。

The server code is like below, (server was ran with root privilege..)

服务器代码如下,(服务器以root权限运行..)

var net = require('net');
var HOST = '127.0.0.1';
var PORT = 6969;
net.createServer(function(sock) {
    console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
    sock.on('data', function(data) {

        console.log('DATA ' + sock.remoteAddress + ': ' + data);
        sock.write('You said "' + data + '"');

    });
    sock.on('close', function(data) {
        console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
    });

}).listen(PORT, HOST);

console.log('Server listening on ' + HOST +':'+ PORT);

and the client code is like below

客户端代码如下

var net = require('net');
var HOST = '127.0.0.1'; //I set it to server IP address but no luck.. 
var PORT = 6969;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
    console.log('CONNECTED TO: ' + HOST + ':' + PORT);
    client.write('I am Chuck Norris!');
});
client.on('data', function(data) {        
    console.log('DATA: ' + data);
    client.destroy();
});
client.on('close', function() {
    console.log('Connection closed');
});

Is there any configuration that I have to go through, if I want the server to accept socket connections from different machine? Do I have to run server code as production mode (if there is such mode)?? Or, is there limitation in port range?

如果我希望服务器接受来自不同机器的套接字连接,是否需要进行任何配置?我是否必须以生产模式运行服务器代码(如果有这种模式)??或者,端口范围有限制吗?

回答by David Schwartz

Set the server to bind to 0.0.0.0 and set the client to connect to the correct IP address of the server. If the server is listening on 127.0.0.1, it will only accept connections from its local host.

设置服务器绑定到0.0.0.0,设置客户端连接到服务器的正确IP地址。如果服务器正在侦听 127.0.0.1,它将只接受来自其本地主机的连接。