在不同的主机上建立套接字连接时,获取“econndenied”错误

时间:2021-04-26 15:41:43

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 same machine.

如果服务器代码和客户端代码都在同一台机器上,那么它们就可以很好地工作。

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?

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

1 个解决方案

#1


12  

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.0,并将客户端设置为连接到服务器的正确IP地址。如果服务器正在监听127.0.0.1,它将只接受来自本地主机的连接。

#1


12  

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.0,并将客户端设置为连接到服务器的正确IP地址。如果服务器正在监听127.0.0.1,它将只接受来自本地主机的连接。