Home > Mobile >  how to disconnect socket using the global io variable
how to disconnect socket using the global io variable

Time:08-29

I have tried this code here to disconnect all sockets

let map = io.sockets.sockets,
array = Array.from(map, ([name, value]) => ({ name, value }));
for(i=0;i<array.length;i  ){
io.to(array[i].name).disconnect()
}

but io.to().disconnect(); is not a function, unlike socket.dissconect() which is a valid function, is there something that can do what i am trying to do?

CodePudding user response:

My solution for that is a global object named 'sockets'

whenever user connects, I'm setting his socket in the sockets object where the key is the socket.id

const sockets = {};

io.on('connection', socket => {
    sockets[socket.id] = socket;
    socket.on('whatever', () => {
        for (let i in sockets) {
            sockets[i].disconnect();
            delete sockets[i];
        }
    });
});
  • Related