WebSockets
WebSockets is a communication protocol that enables full-duplex, persistent connections between a client (typically a browser) and a server. Unlike HTTP, which is unidirectional and request-based, WebSockets allow both parties to send and receive data continuously without repeatedly reopening connections.
Also known as: WS, WebSocket protocol, Real-time communication channel
Comparisons
- WebSockets vs. HTTP: HTTP is request/response-based, while WebSockets maintain an open connection for continuous data exchange.
- WebSockets vs. Server-Sent Events (SSE): WebSockets support bidirectional communication; SSE is server-to-client only.
- WebSockets vs. REST: REST is stateless and not ideal for real-time updates, while WebSockets are designed for low-latency, real-time interactions.
Pros
- Real-time communication: Ideal for chat apps, multiplayer games, financial dashboards, and live feeds.
- Low overhead: Reduces latency and network traffic compared to repeated HTTP requests.
- Persistent connection: Enables stateful, continuous interaction between client and server.
Cons
- Complexity: More difficult to scale and secure than stateless protocols like HTTP.
- Resource usage: Persistent connections consume more server resources.
- Firewall/Proxy issues: Some intermediaries may block or interfere with WebSocket traffic.
Example
A stock trading platform uses WebSockets to push live price updates to users. Once a WebSocket connection is established, the server streams market data in real time to the client’s browser without needing new requests for every update.