客户端加入时未调用事件“connect”

时间:2015-08-12 20:09:57

标签: node.js telnet

对于以下发布/订阅示例,我无法使其工作。 我运行脚本,然后用

启动命令窗口
  

telnet 127.0.0.1 8888

然后命令窗口变为全黑。我甚至没有看到预期的joined!消息,但是当我输入内容时,我确实得到written

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);
        console.log('joined!')
    });
    client.on('data', function(data){
        data = data.toString();
        channel.emit('broadcast', id, data);
        console.log('written');
    });
});

server.listen(8888);

我正在使用具有通用客户端telnet功能的Windows 10。 我也打开了端口8888,虽然它运行在'localhost'

我错过了什么吗?或者是什么原因因为'connect'事件没有被提出?(这引起channel.emit('join', id, client)永远不会被执行

1 个答案:

答案 0 :(得分:1)

client.on('connect', ...)对服务器端(仅客户端)没有意义。您拥有该回调的回调是客户端连接时调用的回调。所以这样做:

var server = net.createServer(function(client){
    var id = client.remoteAddress + ':' + client.remotePort;
    channel.emit('join', id, client);
    console.log('joined!')
    client.on('data', function(data){
        data = data.toString();
        channel.emit('broadcast', id, data);
        console.log('written');
    });
});