1
votes

Is there any role of socket.io rooms in making a real time multiplayer game like Quizup? i have written this code for matchmaking of two players when connected to the server :

var waitingPlayer = null;

io.on('connection',(socket)=>{
    console.log('new user connected');
    if(waitingPlayer == null)
    {
        waitingPlayer = socket;
        waitingPlayer.emit('waiting-message',{
            text:"waiting for an opponent"
        });
    }
    else{
        waitingPlayer.emit('matchFound',{
            text:"Match Found"
        });
        socket.emit('matchFound',{
            text:"Match Found"
        });
    }
}
1

1 Answers

2
votes

Is there any role of socket.io rooms in making a real time multiplayer game like Quizup?

Sort of, but not really.

Socket.io rooms are the following:

  1. A collection (in the programming sense) that allows you to easily keep track of a grouping of sockets.
  2. An easy way to emit a message to a group of sockets with one command.
  3. An easy way to emit a message to everyone in a group (except yourself) with one command.
  4. Rooms are not exclusive either so a given socket can be in as many rooms as you want.
  5. Server-side functionality only. A client can't access rooms, can't put itself in a room, can communicate directly with rooms. Any of that type of functionality has to be done by asking the server to do it for you.

And, that's pretty much what they are.

There is no matchmaking functionality built in to rooms. You could use rooms as a collection management tool for both a waiting room and for individual matches, but you'd be implementing the match making logic yourself and just using the rooms as collections (a convenient tool for keeping track of one or more sockets).

For example, you could make a "waitingRoom", room in socket.io where you put any socket that wants a match, but doesn't yet have one. And, then as soon as you want to start up another game, you could randomly pick two sockets out of the waitingRoom collection and start up a match between them. But, in that scenario you'd really just be using rooms as a collection tool, nothing else. You could just as easily have your own array of sockets that you called a waitingRoom too.

In the code you show, if you never have more than one waiting player, then you can just keep that in the one variable like you are. Your existing scheme seems like it needs more logic for when a socket disconnects from a game in progress and the other socket then wants to find a game again. And, you need to handle the case where waitingPlayer disconnects too.