处理node.js中的字节流

时间:2011-08-05 11:12:27

标签: node.js tcp

出于教育目的,我正在使用TCP创建与node.js的一些聊天。

我正在使用Windows控制台连接我的节点服务器,但是当我输入时,所有字符都是逐个流式传输的。他们没有成为弦乐。我如何设法处理这些流,以便我的用户不能写出完整的单词。

我的代码:

var net = require("net");

Array.prototype.remove = function(e) {
  for (var i = 0; i < this.length; i++) {
    if (e == this[i]) { return this.splice(i, 1); }
  }
};

function Chatter(stream) {
  this.name = null;
  this.stream = stream;
}

var chatters = [];

var server = net.createServer(function(stream) {
    var chatter = new Chatter(stream);
    chatters.push(chatter);

    stream.setTimeout(0);
    stream.setEncoding("utf8");

    stream.addListener("connect", function(){
        stream.write("Hallo, wer bist du?:\n");
    });

    stream.addListener("data", function (data) {
        if(chatter.name == null) {
            chatter.name = data.match(/\S+/);
            stream.write("....................\n");
            chatters.forEach(function(c){
                if (c != chatter) {
                    c.stream.write(chatter.name + " ist dem Chat beigetreten!\n");
                }
            });
            return;
        }

        var command = data.match(/^\/(.*)/);
        if (command) {
            if (command[1] == 'users') {
                chatters.forEach(function(c) {
                    stream.write("- " + c.name + "\n");
                });
            }
            else if (command[1] == 'quit') {
                stream.end();
            }
        }

        chatters.forEach(function(c) {
            if(c != chatter) {
                c.stream.write(chatter.name + ": " + data);
            }
        });
    });

    stream.addListener("end", function(){
        chatters.remove(chatter);
        chatters.forEach(function(c) {
            c.stream.write(chatter.name + " hat den Chat verlassen.\n");
        });

    stream.end();
    });
});

server.listen(8000);

代码来自this site

的记录

此外:

setEncoding('utf8')应该改变数据的发射,但它对我不起作用: - (

1 个答案:

答案 0 :(得分:2)

问题的解决方案是将所有收到的字符存储在缓冲区中,当遇到END_OF_NICK字符时(例如\n),请使用缓冲区作为名称。

var buffer = ""; // stores received characters
stream.addListener("data", function (data) {
    if(chatter.name == null) { // still receiving characters for the name
        buffer += data; // append received characters to the buffer
        if (buffer.indexOf('\n') == -1) return; // if there's no END_OF_NICK character, keep waiting for it
        chatter.name = buffer.match(/\S+/); // use the name in the buffer
    // ...
}