简体   繁体   中英

how to disconnect socket using the global io variable

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM