colyseus / colyseus.js

⚔ Colyseus Multiplayer SDK for JavaScript/TypeScript
https://docs.colyseus.io/getting-started/javascript-client/
MIT License
410 stars 107 forks source link

Add in place reconnection functionality for auto-reconnect on "abnormal closure" (error 1006) #146

Open ComplexRobot opened 1 month ago

ComplexRobot commented 1 month ago

Use case:

room.onClose((code) => {
    // Reconnect on abnormal closure 
    if (code === 1006) {
        client.reconnect(room);
        throw new Error("Reconnecting");
    }
});

My reasoning for adding a new event handler onClose is to not alter the function of existing codebases.

onClose handler will happen when the connection closes before onLeave and will cancel leaving and destroying the room if an error is thrown within the callback.

client.reconnect<T>(room: Room<T>) is a new overload. It will connect in place to an existing room the user is already connected to, therefore not invalidating the state of the existing room and allowing it to be reused.