3

再会。

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 的生成器更改为 strong inc "i" 并省略 ...if (id != senderId)... 但不工作!!!

4

1 回答 1

6

当回调函数tonet.createServer被调用时,它已经暗示了一个客户端连接。另外,我认为该connect事件甚至不是由net.createServer无论如何生成的。

connect因此,与其在发出“join”之前等待事件,不如立即发出它:

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);
  });
});
于 2013-11-09T16:53:24.983 回答