metalaureate metalaureate - 3 months ago 15
Node.js Question

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

Answer

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