WebSocket
WebSocket is a protocol that keeps a single connection open so the client and server can send messages to each other at any time. Normal HTTP is request-response: the client asks, the server answers, the connection closes. WebSocket breaks that pattern and enables real-time, bidirectional communication.
The problem it solves
With plain HTTP, the server cannot push data to the client. To get updates, clients often poll: ask again and again.
HTTP polling (wasteful):
Client: any news? Server: no
Client: any news? Server: no
Client: any news? Server: yes! here it is
WebSocket (efficient):
Client <==== open connection ====> Server
Server: here is an update (whenever it happens)
The handshake
A WebSocket starts life as an HTTP request that asks to “upgrade” the connection.
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
After the 101 response, the TCP connection stays open and both sides exchange messages freely.
Using it
const socket = new WebSocket("wss://example.com/chat");
socket.onmessage = (event) => {
console.log("server says:", event.data);
};
socket.onopen = () => socket.send("hello");
WebSocket vs HTTP polling
Polling WebSocket
Direction client asks both ways
Latency high low
Overhead repeated reqs one connection
Server push no yes
Advantages
- Real-time, low-latency, two-way messages.
- Less overhead than constant polling.
- The server can push without being asked.
Disadvantages
- A persistent connection uses server resources per client.
- Scaling many open connections needs care.
- Must handle reconnects when the network drops.
- Not ideal for simple request-response, where REST is simpler.
When to use it
Use WebSocket for chat, live dashboards, collaborative editing, multiplayer games, and live notifications. For occasional data fetches, stick with regular HTTP requests.