PubSub服务器示例:消息如何广播?

我正在研究Node.js in Action书,我对第3章的PubSub服务器例子有点困惑。这个例子允许用户通过telnet连接到服务器,并相互广播消息。 代码如下:

var events = require('events') , 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 the chat.\n"); }); channel.on('shutdown', function() { channel.emit('broadcast', '', "Chat has shut down.\n"); channel.removeAllListeners('broadcast'); }); 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(); if (data == "shutdown\r\n") { channel.emit('shutdown'); } channel.emit('broadcast', id, data); }); client.on('close', function() { channel.emit('leave', id); }); }); server.listen(8888); 

这似乎很清楚。 client.on('data',function(data){...显然是一个客户端提交一个消息之后提交一个消息channel.emit...照顾广播的绑定,但我不明白那个消息是如何广播给所有其他用户。对我来说,似乎必须循环遍历客户端中的所有客户clients{}但这不是代码处理它。任何人都可以向我解释什么后channel.emit('broadcast'... so数据广播给所有的客户?

当客户端连接时,发出“连接”。 在'join'事件处理程序中是this.on('broadcast', this.subscriptions[id]); 。 这build立了一个新的(附加的)“广播”事件处理程序,它将任何广播的内容写入新连接的客户端。 所以当一个客户端向服务器发送数据时,会发出“广播”,触发每个连接的客户端的“广播”事件处理程序,然后将这个广播数据写入每个连接的客户端。