这段内容出自书籍《Node.JS实战》,第3章,例子11,第52页。
var events = require('events');
var net = require('net');
var channel = new events.EventEmitter();
channel.clients = {};
channel.subscriptions = {};
//Add a listener for the join event that stores a user’s client object,
//allowing the application to send data back to the user.
channel.on('join', function(id, client) {
console.log('join fired');
channel.clients[id] = client;
this.subscriptions[id] = function(senderId, message) {
console.log('broadcast fired');
//ignore data if it’s been directly broadcast by the user.
if (id != senderId) {
this.clients[id].write(message);
}
}
//Add a listener, specific to the current user, for the broadcast event.
this.on('broadcast', this.subscriptions[id]);
});
var server = net.createServer(function(client) {
var id = client.remoteAddress + ':' + client.remotePort;
client.on('connect', function() {
console.log('connect fired');
//Emit a join event when a user connects to the server, specifying the user ID and client object.
channel.emit('join', id, client);
});
client.on('data', function(data) {
console.log('data fired');
data = data.toString();
//Emit a channel broadcast event, specifying the user ID and message, when any user sends data.
channel.emit('broadcast', id, data);
});
});
server.listen(8888);
这个聊天应用可以做到以下几点:
"如果你打开几个命令行,你会发现在一个命令行中输入的任何内容都会被其他命令行回显。"
我添加了console.log()事件来尝试调试发生了什么。但是我唯一得到的日志是发送消息时的"data fired"。虽然我能够启动服务器,并通过telnet连接到它,但是输入的任何消息都不会回显到任何客户端(包括发送消息的客户端)。
有人能解释一下:
- 为什么这个不起作用
- 是否高效或推荐的代码结构
- 如何改进/纠正它