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

socket.to("room").emit() not doing anything if "room" is socket's own id

Open yang530 opened this issue 1 year ago • 1 comments

Describe the bug Hi, everyone.

I was building a websocket chess game. Following is the repository: https://github.com/yang530/websocket_hex_chess

I found that socket.to("room").emit() does not do anything if the "room" is its own socket id.

  1. I understand that every socket starts out being in its own default room and the room id of the default room is its own socket id.
  2. The server of my application will put all the players and spectators of a on-going game in the same room and broadcasts the move to everyone in the room using the emit() function when one of the players makes a move. The room id of the game is the socket id of the player (the host) who started the game session. This means the other player and the spectators are added to the host player's default room.
  3. I understand that emit() function will exclude the sender itself but in my case, it doesn't not seem to send the message to anyone.
  4. I am pretty sure that all the players and spectators are added to the room correctly.
  5. The relevant code is at the "server.js" file, line 80.

I am not sure if this is a bug or it is intended behavior of socket.to("room").emit(). I don't think this particular case is explained anywhere in the documentation unless I missed something.

Thank you for your attention.

To Reproduce


socket.to(socket.id).emit("message...");

Expected behavior "socket.to(socket.id).emit("message...")" sends message to everyone in the room socket.id except the sender itself.

Additional context I end up using "io.to(game_id).emit("pawn promotion", pieceInfo, socket.id);" instead to circumvent the issue. (Note that game_id is the socket id of the host player.) My client just do an additional check of sender id and ignore the message if it is send by the player who made the move.

yang530 avatar Jun 18 '24 03:06 yang530

Hi!

The room id of the game is the socket id of the player (the host) who started the game session. This means the other player and the spectators are added to the host player's default room.

I think this messes with the library internals.

When you call socket.to(socket.id).emit("message...");, it ignores every socket that are in the room named socket.id, so in your case... it's everyone.

You should rather create your own random string, with crypto.randomUUID() for example.

Reference: https://nodejs.org/api/crypto.html#cryptorandomuuidoptions

darrachequesne avatar Jun 18 '24 14:06 darrachequesne

I think this can be closed now. Please reopen if needed.

darrachequesne avatar Sep 18 '24 10:09 darrachequesne