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

1 回答 1

4

我已经使用客户端实现更新了您的代码。它会起作用的。
在“数据”事件中,回调将具有 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');  });
于 2012-06-29T13:07:44.577 回答