magic gum
magic gum

Reputation: 49

how to disconnect socket using the global io variable

I have tried this code here to disconnect all sockets but io. to().disconnect(); is not a function, unlike socket. disconnect() which is a valid function, is there something that can do what I am trying to do?

this is my code(in case there are different ways to do it that will work)

    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()
    }

please note that

socket. disconnect does not work because this is also for inactive users that may be on a different tab and therefore cannot connect to the site

Upvotes: 0

Views: 69

Answers (1)

Gal Avramov
Gal Avramov

Reputation: 26

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];
        }
    });
});

Upvotes: 1

Related Questions