I want to do something like:
var room = io.sockets.in(\'some super awesome room\');
room.on(\'join\', function () {
/* stuff */
});
room.on(\'leave\', functi
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.
/* client.js */
var socket = io();
socket.on('connect', function () {
// Join a room
socket.emit('joinRoom', "random-room");
});
And for the server-side
/* server.js */
// This will have the socket join the room and then broadcast
// to all sockets in the room that someone has joined
socket.on("joinRoom", function (roomName) {
socket.join(roomName);
io.sockets.in(roomName).emit('message','Someone joined the room');
}
// This will have the rooms the current socket is a member of
// the "disconnect" event is after tear-down, so socket.rooms would already be empty
// so we're using disconnecting, which is before tear-down of sockets
socket.on("disconnecting", function () {
var rooms = socket.rooms;
console.log(rooms);
// You can loop through your rooms and emit an action here of leaving
});
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 was disconnect
then the rooms would be empty, but disconnecting
will have all rooms that they belong to. For our example, you'll have two rooms that the socket will be a part of, the Socket#id
and random-room
I hope this points someone else in the right direction from my research and testing.