WebSockets are a communication protocol that allows two-way, real-time communication between a client (like a browser) and a server over a single, long-lived connection.
Think of them as upgrading the regular HTTP request–response model into an always-open chat line where both sides can speak anytime without repeatedly knocking on the door.
🔹 Why WebSockets exist
Traditional HTTP:
- Client sends a request → Server sends a response → Connection closes.
- If you need continuous updates (like in a chat app), you’d have to keep sending new requests (polling), which is inefficient.
WebSockets:
- One handshake → Connection stays open.
- Both client and server can send messages whenever they want.
- Much faster and more efficient for live data.
🔹 How they work (step-by-step)
- Handshake
- Starts as a normal HTTP request with special headers (
Upgrade: websocket) telling the server to switch to the WebSocket protocol.
- Protocol Upgrade
- Server agrees and switches to WebSocket mode.
- Persistent Connection
- No need to send HTTP headers again.
- Messages travel in both directions instantly.
- Close
- Either side can close the connection when done.
🔹 Real-world use cases