user482594
user482594

Reputation: 17486

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

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

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.

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

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?

Upvotes: 8

Views: 22742

Answers (1)

David Schwartz
David Schwartz

Reputation: 182761

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.

Upvotes: 15

Related Questions