I have a node.js server which keeps track of all “clients” connected to it, using an associative array of sockets, because I need to send some data to specific clients sometimes. The keys in that array are strings composed of
socket.remoteAddress + ':' + socket.remotePort
and values are socket instances passed to the callback provided to net.createServer(…)
Sometimes the clients disconnect for one reason or another and I receive the ‘end’ and then ‘close’ events. I’d like to remove the disconnected clients from my client registry but in the close/end event callbacks, the remoteAddress and remotePort variables are undefined. Can they be retrieved somehow?
To illustrate:
var registry = {}
var server = net.createServer(function (socket) {
socket.on('connect', function(){
registry [socket.remoteAddress + ':' + socket.remotePort] = socket;
});
socket.on('close', function(had_error){
// ******************************************************
// socket.remoteAddress and remotePort are undefined here
// ******************************************************
var id = socket.remoteAddress + ':' + socket.remotePort;
// *************************************************************
if(registry.hasOwnProperty(id)
delete socket.id;
});
});
I think you should use socket.id instead of creating your own object property that might not be unique
UPDATE
Node provides basic http API. Http is stateless. HTTP sessions allow associating information with individual visitors but node doesn’t have a native sessions support.
Take a look at express, it is a nice web framework with sessions support
Also, if you need to send messages in a realtime fashion, take a look at socket.io
UPDATE V2
You can add your own ID property to the socket object: