node.js代码不广播消息

时间:2015-05-06 19:34:36

标签: javascript node.js

我是node.js的新手,我跟随着本书中的代码。代码如下:

const JOIN = "join";
const BROADCAST = "broadcast";
const CONNECT = "connect";
const DATA = "data";
const LEAVE = "leave";
const CLOSE = "close";

var events = require("events");
var net = require("net");

var channel = new events.EventEmitter();
channel.clients = {};
channel.subscriptions = {};

channel.on(JOIN,function(id,client){
    this.clients[id] = client;
    this.subscriptions[id] = function(senderId,message){
        if( id != senderId ){
            this.clients[id].write(message);
        }
    }
    this.on(BROADCAST,this.subscriptions[id]);
});

channel.on(LEAVE,function(id){
    channel.removeListener(BROADCAST,this.subscriptions[id]);
    channel.emit(BROADCAST,id, id + " has left.\n");
});

var server = net.createServer(function(client){
    var id = client.remoteAddress + ":" + client.remotePort;
    client.on(CONNECT,function(){
        channel.emit(JOIN,id,client);
    });
    client.on(DATA,function(data){
        data = data.toString();
        channel.emit(BROADCAST,id,data);
    });
    client.on(CLOSE,function(){
        channel.emit(LEAVE,id);
    });
});

server.listen(8888);  

这应该是一个命令行聊天程序。但是,它不起作用。它没有像预期的那样广播消息。此外,每当有人离开聊天时,它就会出现这个错误:

events.js:195
    throw TypeError('listener must be a function');
          ^
TypeError: listener must be a function
    at TypeError (<anonymous>)
    at EventEmitter.removeListener (events.js:195:11)
    at EventEmitter.net.createServer.id (/home/archenemy/node-workspace/simplechat.js:26:10)
    at EventEmitter.emit (events.js:95:17)
    at Socket.<anonymous> (/home/archenemy/node-workspace/simplechat.js:40:11)
    at Socket.EventEmitter.emit (events.js:95:17)
    at TCP.close (net.js:466:12)   

我该如何纠正?

1 个答案:

答案 0 :(得分:1)

在您的事件处理程序中,您在多个位置使用此代替通道。确保&#39;这个&#39;实际上是指通道对象。请记住,您正在处理此处的回调,而且这个&#39;并不总是意味着在涉及回调时你会想到什么。

channel.on(JOIN,function(id,client){
    channel.clients[id] = client;
    channel.subscriptions[id] = function(senderId,message){
        if( id != senderId ){
            channel.clients[id].write(message);
        }
    }
    channel.on(BROADCAST,channel.subscriptions[id]);
});

channel.on(LEAVE,function(id){
    channel.removeListener(BROADCAST,channel.subscriptions[id]);
    channel.emit(BROADCAST,id, id + " has left.\n");
});