I have a specific socket_id that I want to remove from a room in socket.io. Is there an easy way to do this? The only way I can find is to disconnect by the socket itself.
I have a specific socket_id that I want to remove from a room in socket.io. Is there an easy way to do this? The only way I can find is to disconnect by the socket itself.
Share Improve this question asked Apr 5, 2016 at 4:55 CisplatinCisplatin 2,9984 gold badges39 silver badges59 bronze badges2 Answers
Reset to default 5From the client, you send your own message to the server and ask the server to remove it from the room. The server can then use socket.leave("someRoom")
to remove that socket from a given room. Clients cannot join or leave rooms themselves. Joining and leaving to/from rooms has to be done by the server (because the whole notion of chat rooms only really exists on the server).
Documentation here.
For socket.io version 4.0.0 upwards (Mine is version 4.4.0):
Step #1) You have to get an array of the sockets connected to that socket.id as shown in the code below.
//You can replace the userStatus.socketId to your own socket id, that was what I
//used in my own case
const userSockets = await io.of("/chat").in(userStatus.socketId).fetchSockets();
Step #2) After getting all the socket IDs, you will be given an array containing the individual socket (I got to know this by logging the results from the async and await fetchSockets() method that the io library on the server offered). Then use the .find() method to return the single socket object matching that same socket id again as shown below.
const userSocket = userSockets.find(socket => socket.id.toString() === userStatus.socketId);
// Replace userStatus.socketId with your own socket ID
Step #3) Remove the socket by leaving the group using the .leave() method of the socket.io library as shown below.
userSocket.leave(groupId);
// groupId can be replaced with the name of your room
Final Notes: I hope this helps someone in the future because this was what I used and it worked for me.