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 のジェネレーターを強い inc "i" に変更して ...if (id != senderId) を省略しようとしましたが、機能しませんでした!!!

4

1 に答える 1

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