WebSocket Fundamentals
You'll learn how WebSockets enable real-time, two-way communication between browser and server.
What Makes WebSockets Different
Unlike traditional HTTP requests (including SSE, which is one-way), WebSockets provide full-duplex communication — meaning both client and server can send messages to each other simultaneously, at any time. Think of HTTP like sending letters back and forth, while WebSocket is like having a phone conversation where both people can talk whenever they need to.
The Upgrade Handshake
WebSockets start as a normal HTTP request but then "upgrade" to the WebSocket protocol:
- Client initiates: Browser sends a special HTTP request with
Upgrade: websocketheader - Server responds: If the server supports WebSockets, it responds with status code
101 Switching Protocols - Connection established: The HTTP connection transforms into a persistent WebSocket connection
- Two-way channel open: Both sides can now send messages freely without the request-response pattern
This handshake happens automatically when you create a WebSocket connection — you don't manually manage the upgrade process.
Why Use WebSockets?
Perfect for scenarios requiring instant, bidirectional updates:
- Chat applications
- Live collaboration tools
- Real-time gaming
- Live sports scores or stock tickers
- Multiplayer interactions
Unlike SSE (server-to-client only) or repeated fetch() calls (inefficient polling), WebSockets keep one persistent connection open with minimal overhead, allowing instant data flow in both directions.
Key Takeaway: WebSockets use an HTTP upgrade handshake to establish a persistent, full-duplex connection, enabling real-time bidirectional communication between client and server without the overhead of repeated HTTP requests.