I want to do something like:
var room = io.sockets.in('some super awesome room');
room.on('join', function () {
/* stuff */
});
room.on('leave', function () {
/* stuff */
});
This doesn't seem to work. Is it possible?
To illustrate the desired behavior:
io.sockets.on('connection', function (socket) {
socket.join('some super awesome room'); // should fire the above 'join' event
});
I understand this question is old, but for anyone that stumbles upon this via a google search, this is how I'm approaching it.
Joining a room is something that is pretty easy to account for, even though there aren't native events for joining or leaving a room.
And for the server-side
Where it gets a bit trickier is when they disconnect, but luckily a
disconnecting
event was added that happens before the tear down of sockets in the room. In the example above, if the event wasdisconnect
then the rooms would be empty, butdisconnecting
will have all rooms that they belong to. For our example, you'll have two rooms that the socket will be a part of, theSocket#id
andrandom-room
I hope this points someone else in the right direction from my research and testing.
In Socket.IO, a "room" is really just a namespace, something to help you filter your giant bag of sockets down to a smaller bag of sockets. Calling
io.sockets.in('room').on('something')
will cause the event handler to fire for every socket in the room when the event fires. If that's what you want, something like this should do the trick:Important to note is that you'd get the same effect if you (1) got a list of all sockets in a room and (2) iterated over them, calling
emit('join')
on each. Thus, you should make sure that your event name is specific enough that you won't accidentally emit it outside the "namespace" of a room.If you only want to emit/consume a single event when a socket joins or leaves a room, you'll need to write that yourself, as, again, a room isn't a "thing" as much as it's a "filter".
You can use the native "disconnect" event.