节点js从tcp socket net.createServer读取特定的消息

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

无论我尝试什么,我都无法得到:

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

工作,这总是假的。

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

这是因为数据不是一个string,如果你尝试与===进行比较,你会得到错误,因为types不匹配。 要解决它,你应该比较数据对象与一个简单的==或使用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.jsnetworking库:从“数据”事件获取完整的数据