š WebSockets ā Overview for Web Developers
WebSockets are a protocol that enables real-time, full-duplex communication between a client (browser/app) and a server over a single, long-lived connection.
š§ Unlike HTTP, which is one-way and request-response based, WebSockets allow both client and server to send messages anytime.
š What Are WebSockets?
Introduced in HTML5
Starts as an HTTP request, then “upgrades” to a WebSocket connection
Uses
ws://
orwss://
(secure)
ā Key Features
Feature | Description |
---|---|
š Full-duplex | Two-way communication (client ā server) |
ā±ļø Real-time | No polling, ideal for live updates |
š¶ Persistent | Connection stays open until closed by either party |
š Low overhead | After the handshake, uses fewer bytes than HTTP |
š§° Use Cases
šØļø Live chat apps
š Stock tickers & live dashboards
š® Multiplayer games
š Collaborative editing (e.g., docs)
š Push notifications
š Real-time location tracking
āļø How It Works
Client initiates a connection:
httpGET /chat HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Server accepts and switches protocol:
httpHTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Both can now send messages freely over that socket.
šØāš» Simple WebSocket Client Example
const socket = new WebSocket('ws://localhost:3000');
socket.onopen = () => {
console.log(‘Connected!’);
socket.send(‘Hello Server’);
};
socket.onmessage = (event) => {
console.log(‘Message from server:’, event.data);
};
socket.onclose = () => {
console.log(‘Disconnected’);
};
š§ Server-Side Example (Node.js + ws
)
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 3000 });
server.on(‘connection’, (ws) => {
console.log(‘Client connected’);
ws.on(‘message’, (msg) => {
console.log(‘Client said:’, msg);
ws.send(‘Hello from server!’);
});
});
š Security
Concern | Solution |
---|---|
Use HTTPS | Use wss:// instead of ws:// |
Auth | Send tokens/cookies during handshake |
XSS/XSRF | Use validation, sanitization |
Throttling | Limit connections/messages per IP |
š§ WebSocket vs HTTP vs SSE
Feature | WebSocket | HTTP | SSE (Server-Sent Events) |
---|---|---|---|
Direction | Two-way | One-way | One-way (server ā client) |
Persistent | ā | ā (request/response) | ā |
Real-time | ā | ā | ā |
Supported by all browsers | ā | ā | Partial (not IE) |
š Popular Libraries
Language | Library |
---|---|
Node.js | ws , Socket.IO |
Python | websockets , FastAPI |
Go | gorilla/websocket |
Java | Spring WebSocket , Jetty |
Frontend | native WebSocket , socket.io-client |
ā Summary
WebSocket = | Real-time + Persistent + Bidirectional |
---|---|
Protocol | ws:// or wss:// |
Use for | Chat, games, live feeds, notifications |
Bonus | Lightweight, low latency |