WebSocket — Explained with Examples
WebSocket is a full-duplex communication protocol that provides persistent, bidirectional channels between client and server over a single TCP connection.
WebSocket (defined in RFC 6455) enables real-time, event-driven communication where both client and server can send messages at any time. Unlike HTTP’s request-response model, WebSocket keeps the connection open.
How WebSocket Differs from HTTP
HTTP is like sending a letter and waiting for a reply each time. WebSocket is like making a phone call — once connected, both sides can talk freely without the overhead of establishing a new connection for each message.
Client → Server: HTTP Upgrade request (handshake)
Server → Client: 101 Switching Protocols
─── connection established ───
Client → Server: Message (any time)
Server → Client: Message (any time)
Client → Client: Message (any time)
─── connection stays open ───Example: WebSocket Chat Server
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
server.on('connection', (ws) => {
console.log('Client connected');
ws.on('message', (message) => {
console.log(`Received: ${message}`);
// Broadcast to all connected clients
server.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(`Server: ${message}`);
}
});
});
ws.send('Welcome to the chat!');
});// Client-side JavaScript
const ws = new WebSocket('ws://localhost:8080');
ws.onopen = () => {
ws.send('Hello server!');
};
ws.onmessage = (event) => {
console.log('Server says:', event.data);
};Expected output: Client receives “Welcome to the chat!” and “Server: Hello server!”.
Real-World Analogy
HTTP is like sending postcards — you write, mail, and wait for a response. WebSocket is like a two-way radio — you press to talk, release to listen, and both sides can transmit over the same channel without re-establishing contact each time.
Related Terms
SSE, REST, gRPC, HTTP, API Gateway
Related Tutorial
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro