š WebSockets ā Real-Time Communication for the Web
WebSockets provide a full-duplex, persistent connection between the client and server, allowing real-time communication without repeatedly polling the server.
š§ Unlike HTTP (which is request-response based), WebSockets allow bi-directional communication over a single connection.
š Why Use WebSockets?
Feature | Benefit |
---|---|
š Full-Duplex | Both client & server can send messages any time |
ā” Low Latency | Faster than HTTP polling or long-polling |
š§ Persistent | Stays open until explicitly closed |
š¬ Real-Time | Ideal for chat, gaming, live updates, notifications |
Ā
š¦ Common Use Cases
šØļø Live chat apps
š Real-time dashboards
š® Multiplayer games
š Push notifications
š Collaborative editing (e.g., Google Docs)
āļø How WebSockets Work
Client sends an HTTP request to upgrade the connection:
vbnetGET /chat HTTP/1.1 Connection: Upgrade Upgrade: websocket
Server responds and upgrades the connection:
makefileHTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade
Both sides can now send/receive messages instantly over the open socket.
šØāš» Basic Example (Client)
js
const socket = new WebSocket('ws://localhost:3000');
// Connection opened
socket.addEventListener('open', () => {
console.log('Connected to server');
socket.send('Hello Server!');
});
// Receive messages
socket.addEventListener('message', (event) => {
console.log('Message from server:', event.data);
});
šØāš» Basic Example (Node.js Server with ws
)
bash
npm install ws
js
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 3000 });
wss.on('connection', (ws) => {
console.log('Client connected');
ws.on('message', (message) => {
console.log('Received:', message);
ws.send('Hello from server!');
});
ws.on('close', () => {
console.log('Client disconnected');
});
});
š WebSocket vs HTTP
Feature | WebSocket | HTTP |
---|---|---|
Connection | Persistent | Per request |
Direction | Bi-directional | Client ā Server |
Latency | Low | Higher |
Use Case | Real-time apps | Standard web requests |
Ā
š Security Tips
Use
wss://
(WebSocket Secure) over TLS/SSLAuthenticate users on connection
Handle rate limiting and connection timeouts
Consider using a token or cookie for auth
āļø Libraries & Tools
Stack | Library |
---|---|
Node.js | ws , Socket.IO |
Python | websockets , FastAPI + WebSockets |
Go | gorilla/websocket |
Frontend | Native WebSocket API, Socket.IO client |
Frameworks | Next.js, NestJS, Django Channels |
Ā
š§ WebSocket Alternatives
Tech | Use Case |
---|---|
Server-Sent Events (SSE) | One-way real-time updates |
GraphQL Subscriptions | Realtime with GraphQL |
Polling / Long Polling | Simpler or fallback for older browsers |
MQTT | IoT-focused message transport |
Ā
ā Summary
Feature | Value |
---|---|
Persistent connection | ā |
Real-time bi-directional | ā |
Works in browsers | ā |
Needs upgrade from HTTP | ā |
Ideal for real-time apps | ā |