美好的一天。
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]);
});
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);
});
});
server.listen(8888);
当我运行服务器并通过telnet连接'广播'时,无法正常工作。 “Node.js in Action”中的示例。书籍档案中的代码也不起作用。请帮忙。什么可能错了?我尝试将id的生成器更改为强大的inc“i”并省略... if(id!= senderId)...但是没有工作!!!
答案 0 :(得分:6)
当调用net.createServer
的回调函数时,它已暗示客户端已连接。另外,我认为connect
事件甚至不会由net.createServer
生成。
因此,在发出'join'之前,不要等待connect
事件,而是立即发出:
var server = net.createServer(function(client) {
var id = client.remoteAddress + ':' + client.remotePort;
// we got a new client connection:
channel.emit('join', id, client);
// wait for incoming data and broadcast it:
client.on('data', function(data) {
data = data.toString();
channel.emit('broadcast', id, data);
});
});