2

I am trying to create a simple reply server in node.js

The problem I am having, is that when I telnet into the server, and send a hello, the if loop doesn't catch it, and it goes to the else.

Below is my code:

var net = require('net');

var server = net.createServer(function(socket) {
// Server start
socket.write('Welcome\n');

socket.on('data', function(data) {

        dataReceived(socket, data);
    }); 

});

server.listen(8250);

function dataReceived(socket, data) {
    if(data == 'hello') {
    socket.end('Hi');
    } else {
    socket.write(data);
    socket.end('what??\n');
}
}

Thanks.

3
  • Have you tried console.log(data) ? Commented Jul 19, 2011 at 14:20
  • BTW, you should really be using nc instead of telnet for testing. Commented Jul 19, 2011 at 19:08
  • telnet shows you alot more info, why would you use nc? Commented Jul 20, 2011 at 14:42

2 Answers 2

7

Data is a binary buffer, not a string. See http://nodejs.org/docs/v0.4.9/api/buffers.html.

Use the buffer.toString method to convert to a string.

Also, a new line will be added when hitting enter in telnet. Not sure if line endings vary by os, but in this case I'm stripping \r\n.

function dataReceived(socket, data) {
  data = data.toString('utf8').replace(/\r\n/, '');

  if(data == 'hello') {
    socket.end('Hi');
  } else {
    socket.write(data);
    socket.end('what??\n');
  }
}
Sign up to request clarification or add additional context in comments.

Comments

2

As mentioned, main problem is that you compare Buffer object with string.

There is another problem, most probably not visible in your example.

You don't have control how data is split into packets. 'Hello' sent to your server may result dataReceived called with 'Hel' + 'l' + 'o' buffer 3 times

Correct way to handle 'Hello' input us to create state machine or, more simple and less efficient - buffer all incoming data, look for 'Hello' at the beginning of buffered data, then cut handled data from buffer. There are modules aiming to help to unpack/unframe structured data from input stream, for example node-binary

1 Comment

sometimes.. late at night, i think server creation would just be easier in c

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.