Full duplex communication
The WebSocket API opens a persistent, bidirectional connection between browser and server over a single TCP connection. Unlike polling, both sides can send messages at any time.
- The connection begins as an HTTP upgrade handshake
- Use the ws or secure wss scheme
- Messages flow as text or binary frames
- The connection stays open until either side closes it
The event model
A WebSocket emits four key events.
- open: the connection is established and ready
- message: data arrived from the server
- error: a problem occurred
- close: the connection ended, with a code and reason
When to choose it
WebSockets shine for chat, live dashboards, multiplayer games, and collaborative editing, anywhere low latency two way updates matter. For one directional server pushes only, Server Sent Events can be simpler.
Key idea
A WebSocket upgrades from HTTP to a persistent full duplex channel using open, message, error, and close events, ideal for low latency real time apps.