I'm trying to make my socket.io app scale by switching from a regular data structure that holds all my data, to using redis along with cluster. However, I'm encountering some problems because at some point in the current implementation, I store the socket object along with other properties in this data structure data[socket.id].socket = socket
because in my application sometimes I need to do data[someId].socket.disconnect()
to manually disconnect the socket.
I understand I cannot store objects directly into redis, so I tried using JSON.stringify(socket)
with no success, since socket
is circular. Is there another way to disconnect a socket using only the id
? That way I can store the id
like this data[socket.id].id = socket.id
and maybe call it like data[someId].id.disconnect()
or something. So basically I'm looking for a way to disconnect a socket without having access to the actual socket object (I do have access to the io
object).
Thank you all for your help.
It seems this is done already but not documented anywhere... io.sockets.clients(someId)
gets the socket object regardless of on what instance it is called, so the only thing that is needed is to use io.sockets.clients(someId).disconnect()
and will actually disconnect the client, regardless of the instance it is connected to. I was storing them on my own array without actually needing to.
I do the similar thing like this:
var connTable = {};
function onConnection(socket) {
connTable[socket.id] = socket;
socket.on("close", function(data, callback) {
socket.disconnect();
onDisconnect(socket.id);
});
socket.on('disconnect', function(){
onDisconnect(socket.id);
});
}
function manuallyDisconnect(socket_id) {
connTable[socket_id].disconnect();
}
function onDisconnect() {
//closing process, or something....
}