WebSockets
API - Application Programming Interface
2 min read
This section is 2 min read, full guide is 16 min read
Published Sep 24 2025
8
Show sections list
0
Log in to enable the "Like" button
0
Guide comments
0
Log in to enable the "Save" button
Respond to this guide
Guide Sections
Guide Comments
API
WebSockets is a protocol for full-duplex, bidirectional communication between a client (usually a browser or app) and a server over a single TCP connection. Unlike HTTP, which is request-response, WebSockets allow real-time, continuous data flow in both directions.
Key Features
- Full-duplex communication → Both client and server can send messages independently.
- Persistent connection → One connection stays open, reducing overhead.
- Low latency → Ideal for real-time applications.
- Works over TCP → Typically starts as an HTTP handshake, then upgrades to WebSocket.
- Text or binary messages → Supports JSON, binary data, or custom formats.
WebSocket Connection Flow
- Handshake: Client sends an HTTP request with
Upgrade: websocket
. - Server accepts: The connection is upgraded from HTTP to WebSocket.
- Communication: Client and server exchange messages freely until one side closes the connection.
Advantages
- Real-time communication → Great for chat, notifications, live dashboards, gaming.
- Efficient → Less overhead than repeated HTTP requests or polling.
- Bi-directional → Server can push data without client asking.
Disadvantages
- Persistent connections → Can consume resources on the server for many clients.
- Complexity → Requires handling connection lifecycle, reconnection, and scaling.
- Not always cacheable → Unlike REST responses over HTTP.
Use Cases
- Chat applications (Slack, WhatsApp Web).
- Multiplayer games.
- Live dashboards / analytics.
- IoT devices sending continuous sensor data.
- Real-time notifications (stocks, sports scores).
Security
- WebSocket doesn’t define authentication, so it relies on the initial HTTP handshake:
- Query parameters →
wss://example.com/socket?token=abc123
- Authorisation headers →
Sec-WebSocket-Protocol
or custom headers - Cookies / sessions → Server validates the session before upgrading to WebSocket.
- Query parameters →
- After the handshake, the connection is usually trusted, so auth is checked only at handshake.