Search code examples
node.jstelnet

Event 'connect' not being called when a client joins


For the following publish/subscribe example I cannot manage to make it work. I run the script and then I start the command window with

telnet 127.0.0.1 8888

Then the command window turns completely black. I don't even see the expected joined! message, but when I type something I do get the 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);

I am using Windows 10 with the common client telnet feature. I also opened the port 8888, although it is run in 'localhost'

Am I missing anything? Or what is the reason because the 'connect' event it is not being raised?(this provokes the channel.emit('join', id, client) is never executed


Solution

  • client.on('connect', ...) is not meaningful for server-side (only client-side). The callback you have that line in is what is called when a client connects. So just do this:

    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');
        });
    });