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.
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') {
//...
}
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') {
//...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With