字符串比较失败

3

我已经建立了一个简单的TCP服务器,需要将客户端输入与存储在变量中的硬编码字符串进行比较。

然而,data == username 总是失败。

为什么?我该怎么办?

示例:

var authenticateClient = function(client) {
    client.write("Enter your username:");
    var username = "eleeist";
    client.on("data", function(data) {
        if (data == username) {
            client.write("username success");
        } else {
            client.write("username failure");
        }
    });
}

var net = require("net");
var server = net.createServer(function(client) {
    console.log("Server has started.");
    client.on("connect", function() {
        console.log("Client has connected.");
        client.write("Hello!");
        authenticateClient(client);
    });
    client.on("end", function() {
        console.log("Client has disconnected.");
    });
}).listen(8124);

data 包含什么?它是否包含结尾的换行符? - Sjoerd
我不确定。我尝试将其与“eleeist\n”进行比较,但仍然没有运气。 - Eleeist
1个回答

4
我已经更新了您的代码,并添加了客户端实现。它应该能够运行。
在 'data' 事件中,回调函数将会有 Buffer 类的一个实例。因此,您需要先将其转换为字符串。
var HOST = 'localhost';
var PORT = '8124';

var authenticateClient = function(client) {
    client.write("Enter your username:");
    var username = "eleeist";
    client.on("data", function(data) {
        console.log('data as buffer: ',data);
        data= data.toString('utf-8').trim();
        console.log('data as string: ', data);
        if (data == username) {
            client.write("username success");
        } else {
            client.write("username failure");
        }
    });
}

var net = require("net");
var server = net.createServer(function(client) {
    console.log("Server has started.");
    client.on("connect", function() {
        console.log("Client has connected.");
        client.write("Hello!");
        authenticateClient(client);
    });
    client.on("end", function() {
        console.log("Client has disconnected.");
    });
}).listen(PORT);

//CLIENT
console.log('creating client');
var client = new net.Socket();
client.connect (PORT, HOST, function() {
    console.log('CONNECTED TO: ' + HOST + ':' + PORT);
    client.write('eleeist\n');       
});
client.on('data', function(data) {
  console.log('DATA: ' + data);
  // Close the client socket completely
  //    client.destroy();
});

client.on('error', function(exception){ console.log('Exception:' , exception); });
client.on('timeout', function() {  console.log("timeout!"); });
client.on('close', function() { console.log('Connection closed');  });

与其使用 toString,您应该在流上调用 setEncoding。然后会自动触发 data 事件,并且如果字符串是 UTF8,则字符串将被正确处理。 - loganfsmyth

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接