Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data and string comparison with nodejs

I'm a beginner with node.js and I'm willing to create a TCP server which would give me different answers depending on what it receives.

Here's the server side :



var net = require('net');

var server = net.createServer(function(c) {
    console.log('socket opened');
    c.setEncoding('utf8');
    c.on('end', function() {
        console.log('connection/socket closed');
    });
    c.on('data', function(data) {
        console.log('Data:'+data);
        if(data.toString() == "open"){
            c.write('Answer: opened');
        }else if(data.toString() === "add"){
            c.write('Answer: added');
        }else if(data.toString() === "process"){
             c.write('Answer: processed');
        }
    });
});

server.listen(8080, function() { // start server (port 8080)
    console.log('server started');
});

I simply use telnet to try and see if my code is working. Basically I want the server to answer 'opened' if I send him 'open', 'added' if I send 'add' ... I don't know why but it wont work. I've been trying for an hour already and I'm sure that must be some simple mistake I made but now I can't see anything that would cause this simple echo server not to work properly.
like image 641
Yvann Argentin Avatar asked Mar 05 '14 01:03

Yvann Argentin


2 Answers

I know it's later, but there is a better answer, and I found this googling a similar problem. So here are my 2 cents.

To properly catch all cases (and not just the quirks specific to this single case) you should just use the trim() method

if (data.toString().trim() === 'open') {
    //...
}
like image 145
dboshardy Avatar answered Sep 29 '22 12:09

dboshardy


Your code is OK. When you use telnet, you send text messages out by hitting ENTER key. The text received by the sever ends with '\r\n'. So you should compare two strings like this:

if (data.toString() === 'open\r\n') {
  //...
}
like image 36
bnuhero Avatar answered Sep 29 '22 12:09

bnuhero