Reputation: 41
As i upgraded to version 4.x of socket.io on nodeJs i run into issues with certain things breaking.
Here is 2 issues i am facing one is to get a list of all rooms a socket is part of. When i call
socket.rooms
after a client is connected i get a correct response that list all rooms in a set.
Based on what i read using io.sockets.sockets[536xdN11uf311xkFAAAD].rooms
but that gets me the below error.
TypeError: Cannot read property 'rooms' of undefined
How can i get the rooms for a given socket in 4.x
Also how can i get the socket info for a given socket without calling io.sockets.sockets
then doing a for each on it to find the socket i am looking for.
Upvotes: 0
Views: 628
Reputation: 707158
How can i get the rooms for a given socket in 4.x
socket.rooms
is a Set
object that lists the rooms a given socket is in. This is documented for socket.io v4.
If you have the socket.id instead of the socket object, you can do:
const sockets = await io.in(theSocketId).fetchSockets();
This will be an array of sockets, but if you passed in a socket id, there will be zero or one items in the array depending upon whether that socketid exists or not. This is in the doc here and is a fairly new way to do things.
So, putting these together:
async function getRooms(socketid) {
const sockets = await io.in(socketid).fetchSockets();
if (!sockets.length) {
throw new Error(`socketid ${socketid} is not found`);
}
return Array.from(sockets[0].rooms);
}
Note: you will have deal with promises when using this interface (likely because of the support for remote adapters via redis or other clustered adapters).
Upvotes: 1