开发者

Nodejs streaming

开发者 https://www.devze.com 2023-01-09 09:34 出处:网络
I want to realize a simple client-server connection using Nodejs. But I\'ve encountered with the following problem.

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'开发者_StackOverflow社区);

 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?


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.


use socket.write return value and callback as documented here https://nodejs.org/api/net.html#net_socket_write_data_encoding_callback to know when the data is completly flushed to the kernel . Wait for that to happen and after that call the second write. that way you make sure of the ordering. Regarding the problem of logic separartion of "a" and "b" you might want to design/implement that "protocol yourself, it's not a responsiblity of the (low-level) socket API.

0

精彩评论

暂无评论...
验证码 换一张
取 消