Nodejs Require to see which client had exited

I connected through this nodejs code using telnet. When exiting from telnet, the 'end' event fires but does not show the remote address and port.

var net = require('net');
var server = net.createServer(function(s) {

   console.log('CONNECT:' + s.remoteAddress + ':' + s.remotePort);

   s.on('data', function(data) {
      console.log('DATA: ' + s.remoteAddress + ':' + s.remotePort);
      s.write('You said "' + data + '"');
   });

   s.on('end', function() {
      console.log('END: ' + s.remoteAddress + ':' + s.remotePort);
   });

   s.write('hello\r\n');
});

server.listen(8000, function() {
   console.log('Server started on port 8000');
});

On the server console, i get the following when I quit telnet

END: undefined:undefined disconnected

Any ideas?

The end event is fired when the client has closed the connection. In that case, the default behaviour for net.createServer is to also close the connection (but see below), so there is no more remoteAddress and remotePort at the time your callback is called.

The easiest solution is to just store those values in a variable when the connection is created:

var server = net.createServer(function(s) {
  var address = s.remoteAddress;
  var port    = s.remotePort;
  ...
  s.on('end', function() {
    console.log('END: ' + address + ':' + port);
  });
});

Another option is to enable allowHalfOpen, which will stop the server from closing the connection when the client has closed their side:

var server = net.createServer({ allowHalfOpen : true }, function(s) {
  ...
  s.on('end', function() {
    console.log('END: ' + s.remoteAddress + ':' + s.remotePort);
    s.end(); // !!! close the server side explicitly
  });
});