Socket.IO provides a dynamic list of the rooms that each socket is a member of. We can retrieve this list and use it as needed.
In this recipe, we will create a list of the rooms that our socket is in. The list will be dynamically updated if the socket leaves any of its rooms.
To list the rooms that your socket is in, follow these steps:
On the server, we will add our socket to three distinct groups by default. We will add an event listener that will request to list the rooms for us. When this event is sent, we will emit a response message that contains
socket.rooms
, which is an array that Socket.IO builds dynamically as you join and leave rooms. Take a look at the following code:io.on('connection', function (socket) { socket.join('room1'); socket.join('room2'); socket.join('room3'); socket.on('list.rooms', function () { socket...