๐ WebSocket
WebSocket provides a persistent, bidirectional communication channel between a client and a server over a single TCP connection. Unlike HTTP (request-response), a WebSocket connection stays open, allowing both sides to send messages at any time with minimal overhead.
Why WebSocket for Games
For multiplayer games, you need to send frequent, small updates (player positions, actions, state changes) with low latency. HTTP polling adds unnecessary overhead per request. Server-Sent Events (SSE) only support one-way server-to-client communication. WebSocket gives you two-way, low-latency messaging โ the standard choice for real-time multiplayer.
Connection Lifecycle
- Handshake โ the client sends an HTTP upgrade request; the server responds with a 101 status code to switch protocols
- Open โ messages flow freely in both directions
- Close โ either side can close the connection with a close frame
Binary vs. Text
WebSocket supports both text (JSON strings) and binary (ArrayBuffer) messages. For games, binary is often preferred โ itโs smaller and faster to parse.
Scaling
A single server process has limits on how many concurrent connections it can handle. Scaling WebSocket requires sticky sessions (routing the same client to the same server), a pub/sub layer (like Redis) for cross-server messaging, and strategies for horizontal scaling.