What Are WebSockets?
WebSockets enable persistent, full-duplex communication between a client and a server over a single TCP connection, ideal for real-time applications.
In depth
WebSockets provide a persistent, two-way communication channel between a client (like a web browser) and a server. This technology is crucial for building real-time web applications that require instant data exchange without the overhead of traditional HTTP requests.
The Problem with Polling
Traditional web communication often relies on HTTP requests, which are inherently stateless and uni-directional. For applications requiring live updates, such as chat or stock tickers, clients might resort to "polling." This involves the client repeatedly sending HTTP requests to the server, asking if new data is available. Each poll opens a new connection, sends redundant HTTP headers, and then closes the connection, leading to significant bandwidth waste and increased server load from numerous, often empty, requests.
How WebSockets Work
WebSockets solve this by establishing a single, long-lived connection that allows both the client and server to send data to each other at any time. This is known as full-duplex communication.
The Handshake
The process begins with a standard HTTP request from the client, but with a crucial addition: an `Upgrade: websocket` header. This signals to the server that the client wishes to switch protocols from HTTP to WebSocket. If the server supports WebSockets, it responds with an `101 Switching Protocols` status code. At this point, the underlying TCP connection is transformed from an HTTP connection into a raw WebSocket connection.
Persistent, Bidirectional Communication
Once the handshake is complete, the WebSocket connection remains open. Data is then exchanged through lightweight "data frames" rather than heavy HTTP requests. These frames contain only the message payload, eliminating the constant overhead of HTTP headers. Both the client and the server can push data through this persistent tunnel instantly, enabling true real-time interaction without the need for polling.
Key Takeaways
- WebSockets establish a persistent, two-way communication channel.
- They overcome the limitations of HTTP's request-response model for real-time data.
- A special HTTP handshake initiates the WebSocket connection.
- Data exchange uses lightweight frames, reducing overhead compared to HTTP polling.
- Ideal for applications requiring instant, bidirectional data flow, like live chat or gaming.
Got a different question? SeaThru generates a fresh video for any topic where systems talk or data structures move.
Ask your own question →