Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js reply tcp server

Tags:

node.js

tcp

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.

like image 250
rissicay Avatar asked Mar 12 '26 16:03

rissicay


2 Answers

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');
  }
}
like image 98
Ben Taber Avatar answered Mar 15 '26 05:03

Ben Taber


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

like image 23
Andrey Sidorov Avatar answered Mar 15 '26 06:03

Andrey Sidorov