some fixes for players syncing

This commit is contained in:
Zutatensuppe 2020-12-03 21:11:52 +01:00
parent e75cd7406f
commit 3d1a9ca9c7
5 changed files with 54 additions and 46 deletions

View file

@ -45,7 +45,9 @@ export default {
createGame,
exists: GameCommon.exists,
addPlayer: GameCommon.addPlayer,
playerExists: GameCommon.playerExists,
addSocket: GameCommon.addSocket,
socketExists: GameCommon.socketExists,
removeSocket: GameCommon.removeSocket,
get: GameCommon.get,
getSockets: GameCommon.getSockets,

View file

@ -50,43 +50,19 @@ class WebSocketServer {
return
}
socket.isAlive = true
socket.on('pong', function () {
this.isAlive = true;
})
socket.on('message', (data) => {
console.log(`ws| `, data)
console.log(`ws`, socket.protocol, data)
this.evt.dispatch('message', {socket, data})
})
})
this._interval = setInterval(() => {
this._websocketserver.clients.forEach((socket) => {
if (socket.isAlive === false) {
return socket.terminate()
}
socket.isAlive = false
this.evt.dispatch('close', {socket})
socket.ping(() => { })
})
}, 30000)
this._websocketserver.on('close', () => {
clearInterval(this._interval)
})
}
notifyOne(data, socket) {
if (socket.isAlive) {
socket.send(JSON.stringify(data))
}
}
notifyAll(data) {
this._websocketserver.clients.forEach((socket) => {
this.notifyOne(data, socket)
})
socket.send(JSON.stringify(data))
}
}

View file

@ -109,6 +109,30 @@ wss.on('close', async ({socket}) => {
}
})
const ensurePlayerGame = (gameId, clientId, socket) => {
Game.addPlayer(gameId, clientId)
Game.addSocket(gameId, socket)
Game.store(gameId)
const game = Game.get(gameId)
notify(
[Protocol.EV_SERVER_INIT, {
puzzle: game.puzzle,
players: game.players,
evtInfos: game.evtInfos,
}],
[socket]
)
}
const handlePlayerInput = (gameId, clientId, clientSeq, clientEvtData) => {
const changes = Game.handleInput(gameId, clientId, clientEvtData)
Game.store(gameId)
notify(
[Protocol.EV_SERVER_EVENT, clientId, clientSeq, changes],
Game.getSockets(gameId)
)
}
wss.on('message', async ({socket, data}) => {
try {
const proto = socket.protocol.split('|')
@ -121,24 +145,14 @@ wss.on('message', async ({socket, data}) => {
if (!Game.exists(gameId)) {
throw `[game ${gameId} does not exist... ]`
}
Game.addPlayer(gameId, clientId)
Game.addSocket(gameId, socket)
Game.store(gameId)
notify(
[Protocol.EV_SERVER_INIT, Game.get(gameId)],
[socket]
)
ensurePlayerGame(gameId, clientId, socket)
} break;
case Protocol.EV_CLIENT_EVENT: {
const clientSeq = msg[1]
const clientEvtData = msg[2]
const changes = Game.handleInput(gameId, clientId, clientEvtData)
Game.store(gameId)
notify(
[Protocol.EV_SERVER_EVENT, clientId, clientSeq, changes],
Game.getSockets(gameId)
)
ensurePlayerGame(gameId, clientId, socket)
handlePlayerInput(gameId, clientId, clientSeq, clientEvtData)
} break;
}
} catch (e) {