' ECONNREFUSED'尝试使用套接字通过TCP连接到远程计算机时

时间:2015-04-20 18:10:39

标签: javascript node.js sockets tcp

我在尝试使用node.js net API连接到远程计算机时遇到了一些麻烦。此代码在本地完美运行,但当我尝试使用其他人的机器进行测试时,它会给我一个错误:' ECONNREFUSED'

这是服务器端代码。



var net = require('net');

var HOST = '127.0.0.1'; //local host
var PORT = 18000;

net.createServer(function(sock) {
    
    // We have a connection - a socket object is assigned to the connection automatically
    console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
    
    // Add a 'data' event handler to this instance of socket
    sock.on('data', function(data) {
        
        console.log('DATA ' + sock.remoteAddress + ': ' + data);
        // Write the data back to the socket, the client will receive it as data from the server
        sock.write('You said "' + data + '"');
        
    });
    
    // Add a 'close' event handler to this instance of socket
    sock.on('close', function(data) {
        console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
    });
    
}).listen(PORT, HOST);

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

// using sockets to connect to another computer on TCP 




这是客户端代码:



var net = require('net');

var HOST = '127.0.0.1'; //change this to IP address of the computer I'm trying to connect to
var PORT = 18000; 

var client = new net.Socket();
client.connect(PORT, HOST, function() {

    console.log('CONNECTED TO: ' + HOST + ':' + PORT);
    // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client 
    client.write('I am Chuck Norris!');

});

// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {
    
    console.log('DATA: ' + data);
    // Close the client socket completely
    client.destroy();
    
});

client.on('error', function(data){
	console.log('connection error');

});

// Add a 'close' event handler for the client socket
client.on('close', function() {
    console.log('Connection closed');
});




知道我可能做错了吗?

2 个答案:

答案 0 :(得分:0)

您正在侦听localhost,因此除非客户端在同一台计算机上运行,​​否则它将无法运行。 尝试监听远程计算机可以访问的IP地址,或者尝试监听所有地址(不确定它在js上是如何工作的,但在C上将主机地址作为NULL传递或空字符串(取决于平台)就可以了)

答案 1 :(得分:-1)

ECONNREFUSED表示服务器没有侦听客户端尝试访问的端口。检查服务器系统,查看服务器应用程序是否已打开要侦听的端口。

使用netstat等工具或等效工具查看服务器计算机中已打开的TCP端口。