WebSockets
Introduction
WebSockets are an advanced communication protocol that enables two-way, real-time communication between a client (like a web browser) and a server over a single, long-lived TCP connection.
Standard HTTP (the protocol web browsers use to fetch web pages) works on a request-response model. The client requests information, and the server responds. If the server has new information for the client (like a new chat message or a stock price update), the client has to constantly ask the server ("poll") if there's anything new. This is inefficient, creates latency, and uses unnecessary resources (repeated requests, headers, connection setups/teardowns).
WebSockets were designed to solve this problem for applications needing real-time interaction.
How it Works
- Initial Handshake: A WebSocket connection starts as a standard HTTP request, but with special headers (
Upgrade: websocket,Connection: Upgrade). This is like asking the server, "Can we switch from standard HTTP talking to WebSocket talking?" - Upgrade: If the server supports WebSockets and agrees, it sends back a specific HTTP response (status code 101 Switching Protocols).
- Persistent Connection: At this point, the initial HTTP connection is upgraded to a WebSocket connection. This single TCP connection remains open for the duration of the session (or until explicitly closed).
- Full-Duplex Communication: Once established, data can flow freely in both directions (client-to-server and server-to-client) simultaneously and independently over this open connection. The server can push data to the client without the client having to ask first.
Advantages
- Real-time
- Bi-directional
- Efficient (connection remains open and data frames are smaller than full HTTP request/response)
- Low latency
Common Use Cases
- Chat applications
- Live notifications
- Real-time dashboards
- Multiplayer online games
- Collaborative editing tools