简体   繁体   English

node js 从 tcp socket net.createServer 读取特定消息

[英]node js read specific message from 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);

No matter what I try, I cannot get:无论我尝试什么,我都无法得到:

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

working, it's always false.工作,它总是假的。

I'm connecting via telnet and sending "exit", the server should then go into the "if" loop and say "exit message received".我通过 telnet 连接并发送“exit”,然后服务器应该进入“if”循环并说“exit message received”。 This never happens, can someone shed some light ?这永远不会发生,有人可以解释一下吗? thanks谢谢

That's because data is not a string, if you try to compare with === you will get false because types don't match.那是因为 data 不是字符串,如果您尝试与 === 进行比较,则会得到 false,因为类型不匹配。 To solve it you should compare the data object with a simple == or use socket.setEncoding('utf8') previous to binding the data event.要解决它,您应该将数据对象与简单的 == 进行比较,或者在绑定数据事件之前使用 socket.setEncoding('utf8') 。

https://nodejs.org/api/net.html#net_event_data 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");
});

Note.笔记。 If the data received is going to be big you should concatenate and handle the message comparison at the end of it.如果接收到的数据很大,您应该连接并在其末尾处理消息比较。 Check other questions to handle those cases:检查其他问题以处理这些情况:

Node.js net library: getting complete data from 'data' event Node.js 网络库:从“数据”事件中获取完整数据

I am aware this is quite an old post, when I tried to implement the code in the answer to this question I came across the same problem regardless of having used "==" or utf8 encoding.我知道这是一篇很老的帖子,当我尝试在这个问题的答案中实现代码时,无论使用了“==”还是 utf8 编码,我都遇到了同样的问题。 The issue for me turned out to be that the client I was using was appending a '\\n' character to the end of the exit message thus causing the string comparison to fail on the server.我的问题原来是我使用的客户端在退出消息的末尾附加了一个 '\\n' 字符,从而导致服务器上的字符串比较失败。 Perhaps this is not an issue with telnet and the like but this was the case with netcat.也许这不是 telnet 等的问题,但 netcat 就是这种情况。 Hopefully this sheds some light for anyone else who comes across this post and has the same problem that I did.希望这对遇到这篇文章并遇到与我相同问题的其他人有所启发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM