Nodejs 流 [英] Nodejs streaming

查看:35
本文介绍了Nodejs 流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Nodejs 实现一个简单的客户端-服务器连接.但是我遇到了以下问题.

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

考虑代码

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.");
});

当我运行 client.js 时,有时我只会收到一条消息ab",而不是两条消息a"和b".

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 是一种 stream 协议.管道一端的单个 write 会导致另一端的多次读取",反之亦然.您必须通过在消息中包含长度来明确告诉对方您要发送多少字节;或提供易于识别的消息分隔符.在任何情况下,您都需要循环阅读.

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.

这篇关于Nodejs 流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆