Razvan Alex
Razvan Alex

Reputation: 1802

Make specific socket leave the room is in

I'm trying to unsubscribe a socket and make it leave the room he is in. I know his socket.id, to make you understand better, when the creator of the room leaves, a specific socket/all sockets should leave. Ty!

Upvotes: 2

Views: 2783

Answers (1)

jfriend00
jfriend00

Reputation: 707386

To leave a room, you use this:

socket.leave(roomName);

If you only have the socket.id for the socket, then you can get the socket that corresponds to that id with:

let socket = io.sockets.connected[id];
socket.leave(roomName);

If you want to clear everyone out of a particular room, you can do that like this:

function clearRoom(room, namespace = '/') {
    let roomObj = io.nsps[namespace].adapter.rooms[room];
    if (roomObj) {
        // now kick everyone out of this room
        Object.keys(roomObj.sockets).forEach(function(id) {
            io.sockets.connected[id].leave(room);
        })
    }
}

All this code runs only on the server as rooms are a server-side concept only.

Upvotes: 9

Related Questions