Search code examples
socketsstreamingnode.js

Nodejs streaming


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?


Solution

  • 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.