简体   繁体   中英

socket.io - check how long a person has been in a room

background

So I'm trying to create a queuing system for my game. I want someone to who has waited for a minute to just be assigned against an AI. I'd also like people who have waited longer to have priority in matching opponents who are of similar skill level. I was wondering the best way to go about this. Should I set a setTimeout for the AI assignment and a UTC time to check how long they've been waiting? I'm just wondering how I would cancel the timeout afterwards if they are matched.

timeout:

socket.on('waiting room', function (id) {
    console.log("socket has joined the waiting room", id);
    socket.join("waiting room")
    setTimeout(function() {
        socket.leave("waiting room")
        socket.join("some ai game")
    }, 60000)
})

I suppose gameserver resource is limited in game, then players must wait. So when a gameserver is available, we put the player who waited longest to play. Then the logic would look like something below.

 const waitinglist = [] //user leave waiting const leaveWaiting = (socketid) => { waitinglist = waitinglist.filter((x) => x.socket.id != socketid) } io.on('connection', (socket) => { socket.on('waiting room', function(id) { console.log("socket has joined the waiting room", id); socket.join("waiting room") waitinglist.push({ socket, time: new Date(), }) }) //leave by themselves socket.on('disconnect', () => { leaveWaiting(socket.id) }) socket.on('cancle waiting', () => { leaveWaiting(socket.id) socket.leave("waiting room") }) }) //leave by other logic, like match/ai server available matchResource.on('available', (resource) => { const { socket, time } = waitinglist.shift() socket.leave("waiting room") start_your_game(socket, resource) }) 

a global waitinglist, you can replace it with a module something like waiting-manager

when player enter waiting room , enqueue him

when gameserver is available, get a player from queue top, and let him play

whether player quit or begin play, remove him from the queue

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