metalaureate
metalaureate

Reputation: 7732

Node.js net events don't fire

I have the following example of listening to connection and data events, to echo the result back to other telnet clients listening on port 8888. My telnet sessions connect to locahost fine, but no output is echoed. I am hitting my head against a brick wall trying to figure out what is wrong. The execution doesn't even get as far as the 'connect' event.

/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);

I then run in the command line

node server.js
telnet 127.0.0.1 8888

Upvotes: 13

Views: 4268

Answers (2)

Joachim Isaksson
Joachim Isaksson

Reputation: 180927

The manual has this to say;

net.createServer([options], [connectionListener])
Creates a new TCP server. The connectionListener argument is automatically set as a listener for the 'connection' event.

In other words, your function (client) { already received the connection event, and adding a listener to it when it has already been dispatched has no further effect.

Upvotes: 4

robertklep
robertklep

Reputation: 203359

When the callback to net.createServer is called, that's because of an implicit connection event. So your code should look like this:

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() {
    ...
  });
});

Upvotes: 13

Related Questions