Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly unsubscribe from a socket.io room and destroy it?

I have an internal loop for each socket:

if (!chat.room.list[hash]) { // room has expired
    socket.leave(hash);
    delete chat.user.list[socket.store.data.id].rooms[hash];
    delete socket.store.data.inRooms[hash]; // delete room hash from user store
}

socket.leave(hash) does nothing - socket still receives messages sent to hash room.

As a side note - if I connect with client Anna and client Bob - both receive messages, but if I reconnect with client Bob - Bob cannot send messages to Anna.

Is there somewhere a full socket io API documentation (as I couldn't find socket.leave(room) examples)?

EDIT: Got it! Socket IO saves room handles with slash, so you have to use socket.leave('/'+hash)

like image 668
Kristaps Avatar asked Feb 24 '23 03:02

Kristaps


2 Answers

Rooms in socket.io are implicitly created and implicitly deleted. Basically they are automatically removed when they are empty.

And yes, a preceding / is added to the rooms name internally but you do not need to add this to remove a socket from a room.

Try firing console.log(io.sockets.manager.rooms) whenever a room is created to have a look at what's happening internally.

like image 176
greenimpala Avatar answered Feb 25 '23 18:02

greenimpala


As of 0.8.7 i tried it out and it seems you don't have to add the / (slash) anymore

socket.leave(hash)

Works just fine.

like image 24
andrei Avatar answered Feb 25 '23 16:02

andrei