简体   繁体   中英

socket.io leave room after emitting to it

I would like to know when emit process to a room is done in order to leave room right after. Is it OK to leave the room right after emit? I tried using a callback in emit to room but got a server error so I guess it's not possible. Since I imagine that it's an async process, leaving the room right after emit might not be safe (in a large scale). Thoughts?

 //join all friends to a room Socket.join(SOME_ROOM); //send data to this room io.to(SOME_ROOM).emit('SOME_EVENT', SOME_DATA); //cb function fails if I add one //leave room Socket.leave(SOME_ROOM); //is it safe? 

It is safe to leave the room immediately after calling .emit() . The room is only used to figure out which sockets you intend to send to and that is done synchronously in the io.to() call so that is all figured out by the time the .emit() call returns.

Even if the actual sending of the data to those sockets id done asynchronously (which it is), it no longer matters whether the socket is still in the room or not. The room was only used to initially select which sockets to send to and is not used in the actual sending process itself.

Keep in mind that while a room sounds like an all-powerful concept, all it really is under the covers is a list of sockets.

So, you should be able to do this just fine:

//join all friends to a room
Socket.join(SOME_ROOM);

//send data to this room
io.to(SOME_ROOM).emit('SOME_EVENT', SOME_DATA);

//leave room
Socket.leave(SOME_ROOM); 

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