How can i emit to arrays of connected socket-ids ? #3665
Unanswered
parseshyam
asked this question in
Q&A
Replies: 2 comments
|
There is no built-in way to do that right now. You should be able to use ids.forEach(id => io.to(id));
io.emit("hello");The question has already been asked on the Slack channel, so it may make sense to add |
0 replies
|
You can emit to multiple socket IDs without looping by using Socket.io's built-in room support and the Option 1: Use Rooms (Recommended)Instead of tracking individual socket IDs, have sockets join a room based on your criteria: // When socket connects, join them to relevant rooms
io.on('connection', (socket) => {
socket.join('users-online');
socket.join('user-' + userId);
});
// Emit to an entire room
io.to('users-online').emit('notification', { msg: 'Hello everyone!' });You can also target multiple rooms: io.to('room-1').to('room-2').emit('event', data);Option 2: Emit to an Array of Socket IDsThe const socketIds = ['abc123', 'def456', 'ghi789'];
io.to(socketIds).emit('event', { data: 'hello' });This is equivalent to looping but cleaner and handled internally by Socket.io. Option 3: Target Specific Users via a MapIf you need to emit based on database criteria, maintain a map of userId to socketId: const userSockets = new Map();
io.on('connection', (socket) => {
socket.on('register', (userId) => {
userSockets.set(userId, socket.id);
});
});
// Later, emit to specific users
const targetUserIds = ['user1', 'user2', 'user3'];
const socketIds = targetUserIds
.map(uid => userSockets.get(uid))
.filter(Boolean);
io.to(socketIds).emit('event', data); |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Let's say I have connected socket-id stored in DB's, and i want to emit to multiple socket-id's based on some criteria or conditions
instead of looping over and sending is there any other way to send array of socket-id's or something ?
Like ....emit ( [......socket-id's array.........] ,"data" )
All reactions