Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 771
Dan Avatar asked Jul 26 '10 13:07

Dan


People also ask

Is NodeJS good for streaming?

Nodejs is very good to streaming audio and video, but nodejs is a new technology, so it's don't have a lot of softwares yet.

What is streaming in NodeJS?

What are Streams? Streams are objects that let you read data from a source or write data to a destination in continuous fashion. In Node.js, there are four types of streams − Readable − Stream which is used for read operation. Writable − Stream which is used for write operation.

How do I stream a node js file?

In the copy function, you created an input or readable stream using fs. createReadStream() . You also generated a new name for the destination, output a copy of the file, and created an output or writable stream using fs. createWriteStream() .

Is Netflix built on node JS?

“The front-end engineers were having to write a lot of Java code to produce the website, but they also had to write a lot of JavaScript on the client side. With Node, they can do all their work in JavaScript.” said Kim Trott, director of user interface engineering at Netflix.


1 Answers

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.

like image 127
Nikolai Fetissov Avatar answered Sep 24 '22 16:09

Nikolai Fetissov