Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

String comparison fails

String comparison fails

Problem

I have built a simple TCP server and need to compare client input with hard-coded string stored in variable.

However, the data == username always fails.

Why? What can I do about it?

The example:

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);
Problem courtesy of: Eleeist

Solution

I have updated your code, with client implementation. It will work.
On 'data' event, callback will have instance of Buffer class. so you have to convert to string first.

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');  });
Solution courtesy of: Nachiket

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

String comparison fails

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×