views:

270

answers:

1
+1  Q: 

Nodejs streaming

Hello.

I want to realize a simple client-server connection using Nodejs. But I've encountered with the following problem.

Consider the code

server.js:

var net = require('net'),
    sys = require('sys');

    net.createServer(onConnection).listen(8124);

    function onConnection(socket) {
     socket.setNoDelay(true);

     socket.addListener("connect", function () {
      sys.puts('client connected: ' + this.remoteAddress);
     });

     socket.addListener("data", function (data) {
      sys.puts("message: \n" + data + "\n - end of msg.");
     });

     socket.addListener("end", function () {
      sys.puts('end of connection');
      this.end();
     });
    }

    sys.puts('Server running at 127.0.0.1:8124');

client.js:

var net = require('net'),
 sys = require('sys');

var stream = net.createConnection(8124);
stream.addListener("connect", function(){
 sys.puts('connected');

 stream.write('a');
    stream.flush();
 stream.write('b');
    stream.flush();

});

stream.addListener("data", function(data){
 sys.puts("Message: \n" + data + "\n - end of msg.");
});

When I run client.js I sometimes get only one message 'ab' instead of two messages 'a' and 'b'.

Is there some 'right method' to deal with that?

+1  A: 

TCP is a stream protocol. Single write on one end of the pipe can result in multiple "reads" on the other end, and the other way around. You have to either explicitly tell the other side how many bytes you are sending by including the length in the message; or provide easily recognizable message delimiters. In any case you need to read in a loop.

Nikolai N Fetissov
So, the only 'right method' is to concatenate incoming data and parse it as a whole thing? I thought of this, just want to be sure there is no other methods :)
Dan
You have to treat it as a stream. Parse the bytes as they come, react when complete message is found.
Nikolai N Fetissov