Implementing a simple turn-based board game in node using websockets and my design for this is starting to look a little messy.
Basically i have the following questions
- handle reconnects?? on connect im mapping socket ID -> express session ID... deleting it on disconnect and remapping on connect again.
- Cleaning up inactive users, i.e. user has been disconnected for n time.
- Nesting all socket event listeners inside on('connection')?? is there an alternative/what are pros/cons of it.
It just seems like too much manual tracking of state where i'm likely to miss something as it gets more complex, is there a cleaner way of handling this
class GameManager {
constructor(io) {
let self = this;
self.io = io;
self.lfg = {};
self.games = {};
//socket ID -> session ID
self.sockets = {}
//sessionID -> gameID
self.disconnected = {};
io.sockets.on('connection', function (socket) {
let sessionID = getSessionID(socket);
self.sockets[socket.id] = sessionID;
this.reconnect(sessionID);
socket.on('disconnect', this.disconnect);
socket.on('findMatch', this.findMatch);
});
}
disconnect(socket) {
let sessionID = this.sockets[socket.id];
delete this.sockets(socket.id);
//only add user if they were in-game
self.disconnected[sessionID] = game ID
}
findMatch(socket){
//match user in lfg, create new game, place users into socket room
}
reconnect(sessionID){
if (sessionID in this.disconnected) {
delete this.disconnected[sessionID];
//remove disconnected expiry
}
}
}
Aucun commentaire:
Enregistrer un commentaire