Node.jsnetworking事件不会触发

我有下面的示例来监听连接和数据事件,以将结果回显给在端口8888上侦听的其他telnet客户端。我的telnet会话连接到locahost,但没有输出回显。 我正在撞墙,试图弄清楚什么是错的。 执行甚至没有达到“连接”事件。

/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 

       

网上收集的解决方案 "Node.jsnetworking事件不会触发"

当调用net.createServer的callbacknet.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() { ... }); }); 

手册有这个说法;

net.createServer([options],[connectionListener])
创build一个新的TCP服务器。 connectionListener参数自动设置为“连接”事件的侦听器。

换句话说,你的function (client) {已经接收到连接事件,并且在它已经被调度的时候添加一个监听器就没有进一步的效果了。