我不明白,为什么将参数传递给带有嵌套事件侦听器的事件发射器流所有值?是因为它必须通过上层的"join"侦听器吗?变量信息是否存储在某个地方?
var events = require('events');
var net = require('net');
var channel = new events.EventEmitter();
var i = 0;
var subscriptions;
// IF we have two connections
channel.on('join', function(subs) { // Upper Listener
console.log(subs); // -> output 0 when first client joined and 1 for second
channel.on('broadcast', function(subs2) { // lower listener
console.log(subs); // Stream of all connections: -> 0 and 1 ???
console.log(subs2); // Outputs last connection -> 1
});
});
var server = net.createServer(function(client) {
subscriptions = i++; // variable to pass
channel.emit('join', subscriptions); // pass the same variable
client.on('data', function(data) {
channel.emit('broadcast', subscriptions); // pass the same variable
});
});
server.listen(7000);
这将创建TCP服务器。然后您可以使用tellnet localhost 7000
、
请将channel.on('broadcast',…)替换为channel.one('broad cast',..)。因此,使用'once'订阅,一旦处理,将删除'broadcast'侦听器。
对于每个"加入"订阅,我们都有一个"广播"订阅。比方说,在3次加入后,将有三次订阅"广播"活动。因此,当发射器使用"广播"进行发射时,将调用所有三个订阅。sub的值是以前的值,并且只有sub2被更新。
修改后的代码将如下所示。为了更好地理解,我添加了一些额外的控制台日志。
var events = require('events');
var net = require('net');
var channel = new events.EventEmitter();
var i = 0;
var subscriptions;
// IF we have two connections
channel.on('join', function(subs) { // Upper Listener
console.log("join:subs:"+subs); // -> output 0 when first client joined and 1 for second
channel.once('broadcast', function(subs2) { // lower listener
console.log('came to broadcast');
console.log("broadcast:subs:" + subs); // Stream of all connections: -> 0 and 1 ???
console.log("broadcast:subs2:"+subs2); // Outputs last connection -> 1
});
});
var server = net.createServer(function(client) {
subscriptions = i++; // variable to pass
channel.emit('join', subscriptions); // pass the same variable
client.on('data', function(data) {
console.log('received data:'+data);
channel.emit('broadcast', subscriptions); // pass the same variable
});
});
server.listen(7000);
您可能会考虑将join
和data
事件分开的一个原因是在每个事件期间做不同的事情。例如,在这个要点中(https://gist.github.com/nicholascloud/603ae8ead6769ad9b8b5),我在客户端join
时跟踪它们,然后使用data
处理程序向除发送方之外的所有客户端广播消息。就像这样:https://i.imgur.com/pIDy3JD.png
这可以通过多种方式实现,所以不要担心具体的实现。
还要注意,我的频道订阅是而不是嵌套的。只要它们都是在服务器连接之前完成的,我的通道就应该接收所有触发的事件。