socket.on('data', function(data)
{
console.log(socket.remoteAddress + ":" + socket.remotePort);
}
socket.on('close', function()
{
console.log(socket.remoteAddress + ":" + socket.remotePort);
}
The log from the data handler displays 127.0.0.1:8000
.
The log from the close handler displays undefined:undefined
.
I am trying to keep a list of connected sockets using IP:Port as the key. If I don't know which one closed, how can I remove it from the list? How can I get the IP:Port of the closed socket after it's closed?
This is how I'm keeping track of the clients:
server.on('connect', function(socket)
{
socket.key = socket.remoteAddress + ":" + socket.remotePort;
clients[socket.key] = socket;
socket.on('close', function()
{
delete clients[socket.key];
}
}
Much thanks to mscdex in the Node.js IRC channel for suggesting this solution!
socket.on('connect', function()
{
socket.address = socket.remoteAddress + ":" + socket.remotePort;//save the address in socket object
console.log(socket.remoteAddress + ":" + socket.remotePort);
});
socket.on('data', function(data)
{
console.log(socket.address );
});
socket.on('close', function()
{
console.log(socket.address );
});
just keep the data associate with the socket object.Hope this will help.
The remoteAddress property will be around even after disconnect once https://github.com/joyent/node/commit/8c38b07252d86f4eef91344f8df4f0c3e38bca35 is in a stable version of Node.js. io.js will have it in the next release: https://github.com/iojs/io.js/issues/1157