简体   繁体   中英

Having trouble emitting to multiple users with socket.io

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM