I am struggling to make my own matchmaking in a multiplayer game of two players. I have a button that says "play",and i want if the user presses it to change in database his schema property "inQueue to true" .
So after that i want to search the database to check who also is online and in queue(and meets requirement range for elo eg. player1:1200 ELO player2:1288 ) . But i dont want to send multiple requests until it finds a match.
iI was wondering if is there a way to send the request one time and when mongodb finds a match then return the response. ( i am using the mern stack with the help of sockets too)*
CodePudding user response:
The following middleware attempts to find a match on the database. If that is unsuccessful, another attempt is scheduled for a second later. A JSON response is sent only after a successful attempt, but spaces are sent while waiting in the hope that this prevents a browser timeout.
.get("/path", function(req, res) {
res.type("json");
async function attempt() {
var match = await User.find(...);
if (match)
res.end(JSON.stringify({match: match.username}));
else {
res.write(" ");
setTimeout(attempt, 1000);
}
}
attempt();
});
But I think this is only a poor substitute for the real solution based on web sockets as suggested by balexandre.