2016-01-27 140 views
2
var net = require('net'); 

var HOST = '0.0.0.0'; 
var PORT = 5000; 

// Create a server instance, and chain the listen function to it 
// The function passed to net.createServer() becomes the event handler for the 'connection' event 
// The sock object the callback function receives UNIQUE for each connection 
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 
    if (data === "exit") { 
     console.log('exit message received !') 
    } 

}); 

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

无论我怎么努力,我不能让:节点JS读取TCP套接字特定消息net.createServer

if (data === "exit") { 
     console.log('exit message received !') 
    } 

的工作,它总是假的。

我通过telnet连接并发送“退出”,服务器应该进入“if”循环并说“退出消息收到”。这从来没有发生,有人可以摆脱一些光?谢谢

回答

1

这是因为数据不是字符串,如果您尝试与===进行比较,您将因为类型不匹配而变为false。 要解决这个问题,您应该将数据对象与简单的==进行比较,或者在绑定数据事件之前使用socket.setEncoding('utf8')。

https://nodejs.org/api/net.html#net_event_data

var net = require('net'); 
var HOST = '0.0.0.0'; 
var PORT = 5000; 

net.createServer(function(sock) { 
    console.log('CONNECTED:',sock.remoteAddress,':',sock.remotePort); 
    sock.setEncoding("utf8"); //set data encoding (either 'ascii', 'utf8', or 'base64') 
    sock.on('data', function(data) { 
     console.log('DATA',sock.remoteAddress,': ',data,typeof data,"===",typeof "exit"); 
     if(data === "exit") console.log('exit message received !'); 
    }); 

}).listen(PORT, HOST, function() { 
    console.log("server accepting connections"); 
}); 

注意。 如果收到的数据会很大,您应该在它的末尾连接并处理消息比较。检查其他的问题来处理这些情况:

Node.js net library: getting complete data from 'data' event

+0

编码提示是正确的。但它仍然不能可靠地工作,因为套接字可能不会一次发送完整的请求字节。 “退出”可能分布在几个接收到的缓冲区中,或可能包含在也包含其他数据的缓冲区中。 – Matthias247

+0

你说的对,很多变量可能发生在应该被处理的输入数据中,但为了解决他的问题,telnet不会把他的字符串“退出”,它太小了。 – shuji