I am using socket.io (v4.0.1) to build a chat app with react and node. I would like to get a list of sockets (users) who have already joined a room so that when a users joins a room I can send a notification to them to let them know if there are other people online already. There are a lot of examples how to do this with earlier versions of socket.io but none seem to work with version 4. Here is my server code for this event:
// join a room (chat) with the chat id
socket.on('join chat', ({ chat, userId }) => {
socket.join(chat.id);
// this line is not working
const clients = Object.keys(io.sockets.adapter.rooms[chat.id].sockets);
// does not work
// var roster = io.sockets.clients('chatroom1');
const { users } = chat;
if (!chat.users) return console.log('users not defined');
// for each user in the conversation, send a notification to their own room
// telling them someone joined the chat
// want to let the user who joined (userId) know who is already there
chat.users.forEach(user => {
if (user._id === userId) return;
socket.in(user._id).emit('user joined', userId);
});
console.log(`User with id ${userId} joined chat with id ${chat.id}`);
});
Got an answer to this on Github. Hope this helps someone:
// return all Socket instances
const sockets = await io.fetchSockets();
// return all Socket instances in the "room1" room of the main namespace
const sockets = await io.in("room1").fetchSockets();
// return all Socket instances in the "room1" room of the "admin" namespace
const sockets = await io.of("/admin").in("room1").fetchSockets();
// this also works with a single socket ID
const sockets = await io.in(theSocketId).fetchSockets();
Documentation: https://socket.io/docs/v4/server-instance/#Utility-methods
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With