2013-06-03 5 views
12

次の例では、接続イベントとデータイベントをリッスンし、結果をポート8888でリッスンしている他のTelnetクライアントにエコーバックします。telnetセッションはlocahostに接続しますが、出力はありませんエコーされます。私は何が間違っているのか把握しようと、レンガの壁に頭を打っています。実行は 'connect'イベントまでは到達しません。Node.jsネットイベントが発生しない

/server.js

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; 
     console.log(id); 
     client.on('connect', function() { 
      console.log('A new connection was made'); 
      channel.emit('join', id, client); 
     }); 
     client.on('data', function (data) { 
      data = data.toString(); 
      channel.emit('broadcast', id, data); 
     }); 
    }); 

    server.listen(8888); 

net.createServerへのコールバックが呼び出されたとき、私は、コマンドラインで

node server.js 
telnet 127.0.0.1 8888 

答えて

13

を実行して、それがために、暗黙のconnectionイベントのためです。したがって、あなたのコードは次のようになります:

var server = net.createServer(function (client) { 

    // when this code is run, the connection has been established 

    var id = client.remoteAddress + ':' + client.remotePort; 
    console.log('A new connection was made:', id); 

    channel.emit('join', id, client); 

    client.on('data', function(data) { 
    ... 
    }); 

    client.on('end', function() { 
    ... 
    }); 
}); 
+0

ありがとうございました - それはすべてをクリアしました。 – metalaureate

4

manualはこうです:

net.createServer([オプション]、[connectionListener])
新しいTCPサーバーを作成します。 connectionListener引数は、自動的に 'connection'イベントのリスナーとして設定されます。

つまり、function (client) {は既に接続イベントを受信して​​おり、すでにディスパッチされているときにリスナーを追加してもそれ以上の効果はありません。

関連する問題