0

After the client emits a message to the server, I'm trying to emit that message to every other client in the room, however the original client who sent the message also receives the emit... This seems to go completely against all documentation I've read. My code is as follows:

socket.on('slots', (slots) => {
      console.log(socket.id);
      const [thisRoom] = socket.rooms;
      console.log(thisRoom);
      socket.to(thisRoom).emit('slots', slots);
  });

I'm using socket.io 4.5.3.

Many thanks.

El Xando
  • 49
  • 6
  • Have you tried using [`.broadcast()`](https://socket.io/docs/v3/broadcasting-events/) instead? – node_modules Nov 15 '22 at 14:44
  • .broadcast() goes to all connected clients regardless of room right? I only want it to be received by clients in the same room. – El Xando Nov 15 '22 at 14:48
  • 3
    Could you try `socket.broadcast.to("room").emit("hello", "world");`? Does that work for you? – node_modules Nov 15 '22 at 14:52
  • Unfortunately not, that is exactly the same and goes to every client in the room including the sender. – El Xando Nov 15 '22 at 15:55
  • That is very odd it shouldn't, could you also share the client side code? – node_modules Nov 15 '22 at 17:50
  • It's fairly simple code really... Slots is an array of objects that can be randomised by the user. This is done in a populateSlots function, and at the end of that I have this code: `if (multiplayerData.roomcode){ socket.emit('slots', slots); }` then this code handles receiving the message: `socket.on('slots', (newSlots) => { console.log('received new slots'); slots = newSlots; });` But my sender is console logging that it received new slots, which it shouldn't be. – El Xando Nov 15 '22 at 17:59

1 Answers1

2

Check this answer Send a response to all clients except the sender

// sending to all clients except sender
socket.broadcast.emit('message', "this is a test");

Please note that broadcasting is a server-only feature. Therefore you need to configure this in the server.

io.on('connection', (socket) => {
  socket.on('chat message', msg => {
    socket.broadcast.emit('chat message', msg);
  });
});