Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
72
rated 0 times [  79] [ 7]  / answers: 1 / hits: 79198  / 10 Years ago, wed, march 5, 2014, 12:00:00

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.


More From » node.js

 Answers
8

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') {
//...
}

[#72147] Tuesday, March 4, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
breap

Total Points: 606
Total Questions: 96
Total Answers: 108

Location: Djibouti
Member since Sun, Feb 27, 2022
2 Years ago
breap questions
Thu, Jun 24, 21, 00:00, 3 Years ago
Wed, Mar 18, 20, 00:00, 4 Years ago
Mon, Oct 7, 19, 00:00, 5 Years ago
;