0

I'm working on an educational project - online checkers (draughts) game and i'm still not feeling comfortable enough with socket.io.

What i'm trying to do is this - When a player wants to invite another player to a game room to play, using the socket.io I want to send both of the players from the lobby to the game room. Only they get sent to the game room, meaning that even if there are hundreds of players inside the lobby, only the 2 players that wants to play get redirected to the game room.

When player 1 clicks on a button, I emit his details and player's 2 details (The player that player 1 has chosen to play against) to the server as seen below:

socket.emit("SendPlayersToRoom", { player1, player2}, socket.id)

The socket.id argument is the socket.id of player 1. player 2 is an object that already includes his socket id at player2.id.

Next, I receive the information at the server side and then I try to emit this only to players 1 and 2, as seen below:

socket.on("SendPlayersToRoom", ({player1, player2}, id) => {
        io.to(id).to(player2.id).emit("sendToRoom");
    })

Finally, I receive the info at the client side where it should redirect both players to a new room where they can play:

socket.on("sendToRoom", () => {
        location.href = `/game-room?p1=${player1.username}&p2=${player2.username}`                
    })

What actually happens with this code is that player 1 (The one who initiated the game invitation) gets sent to the room without player 2, player 2 stays at the lobby as if nothing happened.

What am I missing here? What am I doing wrong?

YarsCode
  • 11
  • 1
  • 6

1 Answers1

0

You have a unique id for your room. Make sure both sockets join it. socket.join(id) - use this for both your sockets.

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
  • Both of the players have joined the lobby, I also have a chat inside the lobby, where players can see messages from each other, and this works great, because as I mentioned before - both players has joined the 'lobby' room. Is this what you meant? If you meant something else, please explain further. Thank you for your answer. – YarsCode Jun 16 '21 at 14:46
  • No, but they should join the room too right? socket.join() is for manually making sockets join a room. – Tushar Shahi Jun 16 '21 at 14:48
  • Okay I think I understand now, I will try that. Thanks :) – YarsCode Jun 16 '21 at 14:49
  • Do share what happens. – Tushar Shahi Jun 16 '21 at 15:12