简体   繁体   中英

How to handle adding players of game to socket room with socket.io

So on my front end I have the controller call joinPublicGame when a player clicks join game.

$scope.joinPublicGame = function() {
            Socket.emit('join public game');
};

Then on the server I have

    // Player requests to join a public game
    socket.on('join public game', function() {
        console.log(socket.request.user.username);
        // add player to queue
    });

When there are enough players in the queue a game room is created, how can I join the players to the socket room with something like socket.join(game_id) . I wont know the game_id until the game is created though so the queue would be calling some sort of function to join the players.

From what it sounds like, you have a many-to-one relationship of players to a game room. Your server will have to enforce this semantic through something like a "game room controller" which holds the list of sockets, handles merging of events, and updating the relevant clients of any changes. Keep as much of the "state of the room" in this controller so that there aren't any discrepancies between what the clients see.

Example steps for an approach:

  1. Client emits "join game" event.
  2. Server listens to "join game" event and adds their userID info and any other relevant info (like the socket instances themselves) to an object that gets queued up.
  3. When the queue has enough people, it sends the list of the previous objects to a game room controller.
  4. The game room controller sets up any state initialization and begins talking to clients so that their UIs can update and the room can begin.

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