Why WebSockets Were Needed
With polling/long polling:
- Client keeps asking the server repeatedly
- Many unnecessary HTTP requests
- Higher latency
- Waste of bandwidth
WebSockets solve this by creating:
A persistent, full-duplex (two-way) connection over a single TCP connection.
What Is a WebSocket?
A WebSocket is a protocol that allows:
- Continuous connection between client and server
- Bi-directional communication
- Low latency messaging
- Minimal overhead after connection is established
Instead of:
request → response → closeYou get:
open connection → send/receive anytime → close when doneHow WebSockets Work
1 Starts as HTTP
The connection begins as a normal HTTP request. In order to start the connection, clients sends a http GET request with a upgrade header, so that the server know that this is a upgrade request.
Client sends:
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: random_key
Sec-WebSocket-Version: 13This is called the HTTP Upgrade request.
2 Server Upgraded the Connection
If server supports WebSockets. It responds with status 101 and return error code if not.
If any code other than 101 is returned from the server, Clients has to end the connection.
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: generated_keyNow:
- HTTP is done.
- The TCP connection remains open.
- Communication switches to WebSocket protocol.
3 Persistent Full-Duplex Communication
Now both sides can send messages anytime:
Client ⇄ ServerNo repeated HTTP headers.
No repeated handshakes.
Jut lightweight frames.
WebSocket Frames
After upgrade, data is sent in frames.
Each frame contains:
- Opcode (text, binary, ping, pong, close)
- Payload length
- Masking key (for client messages)
- Actual data
Example text frame:
{ "message": "Hello!" }Binary data (e.g., file chunks) also supported.
Connection Lifecycle
- Client connects
- Server accepts
- Messages flow both ways
- Either side can close connection
Close frame includes a status code (e.g., 1000 = normal closure).
Security
WebSockets can be:
ws://(plain)wss://(secure, uses TLS)
Secure WebSockets (wss://) use the same TLS handshake as HTTPS.
Leave a comment
Your email address will not be published. Required fields are marked *
