简体   繁体   中英

How to listen for Room events

So to clarify, I know the client should send a message such as 'join-room' to the server for handling, and thats fine, and I know I can do the same for 'leave-room'.

What I want is to actually listen to the events themself, because say if a client disconnects, I need to send a message to the rooms affected, as when a client disconnects then they automatically leave all rooms.

So I want something like;

socket.on('join' function() {
// send message
});

socket.on('leave' function() {
// send message
});

So that if the user closes the window (which disconnects the client, and then triggers all the rooms to be left) I can send a message out.

I am using the latest socket.io, with the redis adaptor.

Also;

What is the most efficient way to list all the rooms a particular socket is in, as technically I think the disconnect event should contain the client_id so I could do this manually.

The key thing is clarity and stability, although I am open to alternate approaches (must still use socket.io).

Thanks

So if I understood correctly your main question: you want to listen to the events of joining and leaving a room in the implementation itself such that socket.join(room_id) should fire that event you want to listen to.

The thing is the docs dont mention any ways of listening to that event. In fact, the implementation itself shows no sign of firing an event when joining a room. My guess is that you will have to implement the join_room/leave_room system to handle that.

As for the sub-question, the socket object contains an array called rooms such that socket.rooms contains all the rooms the socket is currently in.

This is probably what you're looking for :

socket.on('disconnect', function() { for(var room in socket.rooms) { //do stuff before the client close the connection and leave the rooms } });

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