简体   繁体   中英

node.js code doesn't broadcast messages

I am new to node.js and I was following along with the code in the book. The code is as follows:

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);  

This is supposed to be a command line chat program. However, it doesn't work. It doesn't broadcast messages as it is supposed to. Also, whenever someone leaves the chat, it blows up with this error:

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)   

how do I correct this?

In your event handlers, you are using this instead of channel at several places. Make sure 'this' actually refers to the channel object. Remember you are dealing with callbacks here and 'this' does not always mean what you think it would when callbacks are involved.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM