Avinash
Avinash

Reputation: 325

Send message to other rooms in Socket.io

I Know how to send message to all the clients in the same room. I am using below code to send message to clients in the same room (server side).

io.to(Array.from(socket.rooms)[1]).emit("send message","We are in Same room")
//Array.from(socket.rooms)[1] -> getting room number from the map

But now I want to send message to All the clients who are not in current room.

Upvotes: 0

Views: 226

Answers (1)

Cássio Lacerda
Cássio Lacerda

Reputation: 1634

Get the array with socket IDs from specific room and using that array to exclude from all connected sockets:

const socketsFromRoom = Array.from(await io.in("my_room").allSockets());

Array.from(await io.allSockets())
  .filter((socketId) => !socketsFromRoom.includes(socketId))
  .forEach((socketId) => {
    io.sockets.sockets.get(socketId).emit("send_message");
  });

Upvotes: 2

Related Questions