EXERCISE
1HTTP is request-response only. WebSockets enable servers to push data to clients instantly. This is how real-time apps work.
Save
HTTP is one-way: Client always initiates. only responds.
Server cannot push data without client requesting first.
Problem: How to build real-time ?
Examples:
Short polling: Client repeatedly asks "any updates?"
Every 2 seconds:
Client: "Any new messages?"
Server: "No"
Client: "Any new messages?"
Server: "No"
Client: "Any new messages?"
Server: "Yes: {message}"
Problems:
WebSocket: Persistent, bidirectional connection.
Key feature: After setup, either side can send data anytime.
Flow:
Client request:
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Server response:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Connection upgraded. Now WebSocket protocol. No more HTTP.
Client Server
| |
|--- HTTP Upgrade ------->|
|<-- 101 Switching --------|
| |
|=== WebSocket Open ===|
| |
|--- "Hello" ------------>|
|<-- "Hi there" ----------|
|<-- "New notification" --|
|--- "Got it" ----------->|
After upgrade: Messages flow freely. No request/response pattern.
Scenario: Chat app. Sending 10 messages.
HTTP (new connection each time):
Message 1: 3-way + request + response + 2-way = 5 messages
Message 2: 3-way + request + response + 2-way = 5 messages
...
Message 10: 3-way + request + response + 2-way = 5 messages
Total: 50 network messages
WebSocket:
Initial: 3-way handshake + upgrade
Message 1: Send (1 packet)
Message 2: Send (1 packet)
...
Message 10: Send (1 packet)
Final: Close
Total: 13 network messages
WebSocket is 4× more efficient!
Chat apps (WhatsApp, Slack):
Messages arrive instantly. No polling needed.
Server pushes message to recipient via WebSocket.
Live notifications (Instagram, Twitter):
New like? Server pushes instantly.
No need for app to constantly ask "any updates?"
Stock trading (Robinhood, Zerodha):
Prices update multiple times per second.
Server streams price updates continuously.
Collaborative editing (Google Docs, Figma):
See others typing in real-time.
Every keystroke sent via WebSocket, broadcast to all users.
Live sports (ESPN apps):
Goal scored? See it within 1 second. No refresh needed.
Persistent connections are expensive.
Memory: Each connection holds server resources (TCP socket, buffers).
100,000 users = 100,000 open connections.
Server requirements: Need specialized servers for high connection counts (, Go, Erlang).
Traditional servers (Apache): Designed for short HTTP requests. Poor WebSocket performance.
Trade-off: Amazing user experience. Higher infrastructure cost.
Simple : Fetching profile? Use HTTP. No need for persistent connection.
Infrequent updates: Notification once per hour? HTTP polling fine.
Public APIs: Hard to manage thousands of persistent connections from unknown clients.
Mobile on cellular: WebSocket connections interrupted by network switches. HTTP with retries more reliable.
Use only when truly needed. For real-time, bidirectional communication.
Socket.IO: Popular library for WebSockets.
Features:
Chat example:
Server:
const io = require('socket.io')(3000);
io.on('connection', (socket) => {
socket.on('chat message', (msg) => {
io.emit('chat message', msg); // Broadcast
});
});
Client:
const socket = io('http://localhost:3000');
socket.emit('chat message', 'Hello!');
socket.on('chat message', (msg) => display(msg));
That is it! Basic real-time chat in under 10 lines.