Ask anything about this article
Hi! I've read this article.
What would you like to know?
@farhan
HTTP was designed for request-response communication — the client asks, the server answers. But what about real-time data? Chat messages, live notifications, stock tickers, multiplayer games — all need the server to push data to the client instantly.
javascript// Client asks every 2 seconds: "Any new messages?"
setInterval(async () => {
const response = await fetch('/api/messages');
const messages = await response.json();
updateUI(messages);
}, 2000);
Problems: Wastes bandwidth, adds server load, 2-second delay
javascriptasync function longPoll() {
const response = await fetch('/api/messages?wait=true');
const messages = await response.json();
updateUI(messages);
longPoll(); // Immediately reconnect
}
Better but still creates new connections constantly.
WebSockets provide a persistent, bi-directional connection between client and server. Once established, both sides can send data at any time with zero overhead.
HTTP: Client → Request → Server → Response → Connection Closed
WebSocket: Client ↔ Server (persistent, bi-directional)
typescriptimport express from 'express';
import { createServer } from 'http';
import { Server } from 'socket.io';
const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, {
cors: { origin: "http://localhost:3000" }
});
io.on('connection', (socket) => {
console.log('User connected:', socket.id);
// Listen for messages
socket.on('chat:message', (data) => {
// Broadcast to all connected clients
io.emit('chat:message', {
id: Date.now(),
user: data.user,
text: data.text,
timestamp: new Date()
});
});
// Handle typing indicator
socket.on('chat:typing', (user) => {
socket.broadcast.emit('chat:typing', user);
});
// Handle disconnect
socket.on('disconnect', () => {
console.log('User disconnected:', socket.id);
});
});
httpServer.listen(3001, () => {
console.log('WebSocket server running on port 3001');
});
tsximport { useEffect, useState } from 'react';
import { io } from 'socket.io-client';
const socket = io('http://localhost:3001');
function Chat() {
const [messages, setMessages] = useState([]);
const [input, setInput] = useState('');
useEffect(() => {
socket.on('chat:message', (message) => {
setMessages(prev => [...prev, message]);
});
return () => socket.off('chat:message');
}, []);
const sendMessage = () => {
socket.emit('chat:message', {
user: 'John',
text: input
});
setInput('');
};
return (
<div>
{messages.map(msg => (
<div key={msg.id}>
<strong>{msg.user}:</strong> {msg.text}
</div>
))}
<input value={input} onChange={e => setInput(e.target.value)} />
<button onClick={sendMessage}>Send</button>
</div>
);
}
✅ Chat applications
✅ Live notifications
✅ Real-time dashboards
✅ Multiplayer games
✅ Collaborative editing (Google Docs)
✅ Live sports scores
✅ Stock/crypto tickers
❌ Static content delivery
❌ File uploads/downloads
❌ CRUD operations
❌ Infrequent data updates (use SSE or polling instead)
If you only need server-to-client communication (no bi-directional), use SSE:
typescript// Server
app.get('/events', (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
setInterval(() => {
res.write(`data: ${JSON.stringify({ time: new Date() })}\n\n`);
}, 1000);
});
// Client
const source = new EventSource('/events');
source.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log(data);
};
WebSockets unlock a whole new category of applications. Once you start building real-time features, you'll wonder how you ever lived without them.