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!
Asked
Active
Viewed 2,635 times
1 Answers
9
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.

jfriend00
- 683,504
- 96
- 985
- 979
-
Ty, gonna bookmark this answer, that's exactly what I was looking for ;) – Razvan Alex Oct 06 '16 at 11:47
-
1hey @RazvanAlex is , in `io.sockets.connected[id].leave(room);` .leave(room) I got an error `TypeError: Cannot read property 'leave' of undefined` can you tell me what happen? my socket version is 2.2.0 – Md Alamin Feb 05 '19 at 06:50