socket.io icon indicating copy to clipboard operation
socket.io copied to clipboard

If a socket leaves its default room, socket.to('room').emit messages will be received by it despite being sender

Open ElXando opened this issue 3 years ago • 4 comments

Describe the bug If a socket leaves the default room which matches its socket id, socket.to('room').emit messages will be receives by the client of the sender, even though the documentation makes no mention of this.

To Reproduce

Please fill the following code example:

Socket.IO server version: 4.5.3

Server

import { Server } from "socket.io";

const io = new Server(3000, {});

io.on("connection", (socket) => {
  socket.leave(socket.id);
  OR
  socket.leaveAll();

  socket.join('TEST');

  socket.on("test", (message) => {
    socket.to('TEST').emit('test', message);
  });
});

Socket.IO client version: 4.5.3

Client

import { io } from "socket.io-client";

const socket = io("ws://localhost:3000/", {});

socket.on("test", (message) => {
  console.log(message);
  // Is logged by sender as well as other clients in the room
});

socket.emit('test', 'hello');

Expected behavior I would not expect that leaving the default room would mean the sender receives a message that otherwise it shouldn't. My idea of leaving the default room is that I can ensure each connected client is only in a single room, and then when emitting to the room they're in I was hoping to use:

const [thisRoom] = socket.rooms;
socket.to(thisRoom).emit('test', message);

Perhaps there is a different expected way to use rooms but it would seem a bit clunky to use const [, second] = socket.rooms if I leave each client in the default room?

Platform:

  • Device: Windows
  • OS: Server 2019 Server, 11 Client

ElXando avatar Nov 18 '22 01:11 ElXando

Hi! I could indeed reproduce the issue.

Yes, that is a surprising behavior, we should definitely fix this in the next major version. Not sure how though.

darrachequesne avatar Nov 30 '22 00:11 darrachequesne

Hey, Is this issue still not fixed? I am facing the same issue in my code.

0xamitr avatar Jan 27 '24 13:01 0xamitr

@0xamitr the behavior is still the same. For now, we strongly suggest not leaving the default room.

darrachequesne avatar Jan 29 '24 17:01 darrachequesne