2013-06-03 88 views
12

我有以下示例來監聽連接和數據事件,以將結果回顯給偵聽端口8888的其他telnet客戶端。我的telnet會話連接到locahost正常,但沒有輸出被呼應。我正試圖弄清楚什麼是錯誤,正在撞到一堵磚牆。執行甚至沒有達到「連接」事件的程度。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); 

然後我在命令行

node server.js 
telnet 127.0.0.1 8888 

回答

13

當回調到net.createServer被稱爲運行,這是因爲隱式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參數自動設置爲「連接」事件的偵聽器。

換句話說,您的function (client) {已經收到連接事件,並且當它已經被分派時添加一個監聽器沒有進一步的效果。