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 连接并发送“exit”,然后服务器应该进入“if”循环并说“exit message received”。这永远不会发生,有人可以解释一下吗?谢谢
最佳答案
那是因为数据不是字符串,如果您尝试与 === 进行比较,您将得到 false,因为类型不匹配。 要解决它,您应该将数据对象与简单的 == 进行比较,或者在绑定(bind)数据事件之前使用 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");
});
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
关于javascript - Node js 从 tcp 套接字 net.createServer 读取特定消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35036439/