In this lesson, you will learn how to design a state-machine-driven reconnection flow that preserves game continuity when a player’s connection drops.
The Lifecycle of a Disconnection
In a robust multiplayer architecture, a disconnection should not be treated as an immediate session termination. Instead, treat it as a transitional state. When a client loses contact, the server must hold the player's entity in a "Ghost" state—keeping their data active in memory for a specific timeout window—rather than destroying the object immediately.
Designing the Reconnection State Machine
To manage this, implement a state machine on the client that tracks the connection status. When the network drops, the client moves into a Reconnecting state. During this time, the UI should provide feedback while the client attempts a handshake to rejoin the existing session using a unique SessionToken (generated during the initial authentication).
The server, upon seeing a "reconnect request" from an existing SessionToken, validates the request and re-syncs the client with the current WorldState.
public enum ConnectionStatus { Connected, Reconnecting, Disconnected }
public class NetworkStateManager : MonoBehaviour {
private ConnectionStatus currentState;
private float timeoutTimer = 15.0f; // Seconds to hold session
void OnNetworkError(NetworkEvent error) {
if (CanAttemptReconnect(error)) {
TransitionTo(ConnectionStatus.Reconnecting);
StartCoroutine(AttemptRejoinSequence());
} else {
TransitionTo(ConnectionStatus.Disconnected);
}
}
}
Critical Recovery Logic
For a seamless transition, the server must not rely solely on the client’s request for data. Upon successful reconnection, the server should perform a "Full State Snap" to ensure the client is synchronized with the latest entity positions and game variables. This prevents the client from drifting into a state of "desync" where their local simulation disagrees with the authoritative server logic.
If the timeoutTimer expires before the client successfully performs a handshake, the server must finally broadcast a disconnect event to all other players and clean up the persistent data for that SessionToken. This ensures that ghost entities do not remain in the game world indefinitely, consuming bandwidth and CPU cycles.
Key Takeaway: Treat disconnections as temporary states by utilizing SessionTokens and a server-side "grace period" that allows clients to resume their previous game state before permanently purging their player data.