What are WebSockets
The Problem with Traditional HTTP
Every HTTP request follows a request-response cycle: the client asks, the server answers, and the connection closes. For most web interactions — loading a page, submitting a form, fetching data — this model works perfectly.
But what if you are building a live chat app? A stock price ticker? A multiplayer game? You need the server to push data to the client the moment something changes, without the client having to ask.
HTTP was not designed for this. Developers invented workarounds.
The Old Workarounds
Short Polling
The client sends an HTTP request every few seconds regardless of whether new data exists:
// Client repeatedly asks: "is there anything new?"
setInterval(() => {
fetch('/api/messages')
.then(res => res.json())
.then(data => updateUI(data));
}, 2000); // every 2 seconds
Problems: Most requests return empty responses. Wastes bandwidth and server resources. Feels laggy — up to 2 seconds of delay.
Long Polling
The client sends a request and the server holds it open until new data is available (or a timeout occurs):
// Server holds the connection open until data arrives
app.get('/poll', (req, res) => {
const timeout = setTimeout(() => {
res.json({ data: null }); // no data arrived in time
}, 30000);
waitForNewData((data) => {
clearTimeout(timeout);
res.json({ data });
});
});
Problems: Better than polling but still involves repeated HTTP overhead. Complex to implement reliably.
WebSockets: Full-Duplex Communication
WebSockets solve this properly. A WebSocket connection:
- Starts as an HTTP request — the client sends a special
Upgradeheader - Upgrades to a persistent connection — both sides agree to switch protocols
- Stays open — either side can send messages at any time without a new request
- Is full-duplex — client and server can send messages simultaneously
This is the fundamental difference: HTTP is half-duplex (one direction at a time), WebSockets are full-duplex (both directions simultaneously, like a phone call).
The WebSocket Handshake
The upgrade from HTTP to WebSocket happens via a handshake:
Client request:
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Server response:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
After the 101 Switching Protocols response, the connection is upgraded and HTTP is no longer used on that socket.
Native WebSocket API in the Browser
// Client-side code
const socket = new WebSocket('ws://localhost:5000');
socket.addEventListener('open', () => {
console.log('Connected to server');
socket.send(JSON.stringify({ type: 'greeting', text: 'Hello!' }));
});
socket.addEventListener('message', (event) => {
const data = JSON.parse(event.data);
console.log('Message from server:', data);
});
socket.addEventListener('close', () => {
console.log('Connection closed');
});
socket.addEventListener('error', (error) => {
console.error('WebSocket error:', error);
});
On the server with Node.js's built-in ws library:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 5000 });
wss.on('connection', (ws) => {
console.log('Client connected');
ws.on('message', (rawData) => {
const data = JSON.parse(rawData);
console.log('Received:', data);
ws.send(JSON.stringify({ type: 'ack', text: 'Got your message!' }));
});
ws.on('close', () => {
console.log('Client disconnected');
});
});
When to Use WebSockets
| Use Case | Best Technology |
|---|---|
| Real-time chat | WebSockets |
| Live notifications | WebSockets or SSE (Server-Sent Events) |
| Multiplayer games | WebSockets |
| Live stock / sports data | WebSockets or SSE |
| Progress updates (file upload) | SSE |
| Standard CRUD (Create, Read, Update, Delete) data | HTTP REST |
WebSockets are ideal when you need bidirectional real-time communication. For one-way server-to-client streams, Server-Sent Events (SSE) are simpler.
Practice Exercise
- Install the
wspackage (npm install ws) in a new Node.js project. - Create a WebSocket server that echoes every message back to the client with a timestamp.
- Open two browser tabs and connect both to your server. Send a message from one and observe it in the server logs.
- Add a connection counter that logs how many clients are currently connected.
Try it yourself
Key Takeaways
- HTTP is half-duplex (request-response); WebSockets are full-duplex (both sides communicate simultaneously over one persistent connection).
- Short polling wastes resources; long polling is better but still adds HTTP overhead; WebSockets eliminate both problems.
- The WebSocket handshake begins as an HTTP request and upgrades to the WebSocket protocol with a 101 Switching Protocols response.
- Use WebSockets for bidirectional real-time features (chat, games); use Server-Sent Events (SSE) for one-way server-to-client streams.
- The browser's native WebSocket API provides open, message, close, and error event listeners for managing the connection lifecycle.
Quick Quiz
1.What is the key difference between HTTP and WebSocket communication?
2.What HTTP status code signals a successful WebSocket upgrade?
3.Why is short polling an inefficient solution for real-time data?
4.When is it better to use Server-Sent Events (SSE) instead of WebSockets?
Ready to go further?
CareerEx gives you structured 12-week training, live classes every Saturday and Sunday, real tutor feedback, and a certificate. Join the next cohort.
Join CareerEx