最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Socket.IO: Remove specific socket_id from room? - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 5

From 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.

发布评论

评论列表(0)

  1. 暂无评论