How does WebSocket work?
What WebSocket is
WebSocket is a network protocol that creates a persistent, two-way connection between a client (browser) and a server over a single TCP channel.
Unlike HTTP:
- HTTP is request-response (the client always initiates);
- WebSocket is a persistent connection, where both sides can send data at any moment.
The basic idea
A regular HTTP request:
Client → Server: give me new data
Server → Client: here is the data
(connection closed)WebSocket:
Client ↔ Server: connection established (once)
From then on they communicate directly, without repeated requestsA simple example
Imagine you are talking to the server on the phone:
- HTTP is like dialing the number again each time, saying one sentence, and hanging up.
- WebSocket is like calling once and talking for as long as you want, in both directions.
How the connection is established (handshake)
- The client opens a connection:
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: <random-key>
Sec-WebSocket-Version: 13- The server responds:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: <hash-key>- After that, the HTTP connection is "upgraded" to WebSocket. It is no longer HTTP, but a persistent, two-way channel over TCP.
What it looks like on the client (in the browser)
Example:
// Create the connection
const socket = new WebSocket('wss://example.com/chat');
// When the connection is established
socket.addEventListener('open', () => {
console.log('Connection open');
socket.send('Hello, server!');
});
// When messages arrive
socket.addEventListener('message', (event) => {
console.log('Message received:', event.data);
});
// On error
socket.addEventListener('error', (err) => {
console.error('Error:', err);
});
// When the connection closes
socket.addEventListener('close', () => {
console.log('Connection closed');
});The ws:// or wss:// prefix (similar to http and https):
ws://- unencryptedwss://- a secure connection (over TLS)
How the server works (in Node.js)
An example with the ws library:
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', (ws) => {
console.log('Client connected');
ws.on('message', (msg) => {
console.log('Received:', msg.toString());
ws.send(`You said: ${msg}`);
});
ws.on('close', () => console.log('Client disconnected'));
});Now any client can connect:
const socket = new WebSocket('ws://localhost:8080');What keeps a WebSocket "alive"
A WebSocket stays open as long as:
- the connection is not interrupted;
- one of the sides does not call
.close(); - a timeout or network error does not occur.
The browser and server can periodically send "pings" (ping/pong) to check that the connection is alive.
Message format
WebSocket transmits data in binary or text form.
On the client, event.data can be:
stringBlobArrayBuffer
You can even send JSON:
socket.send(JSON.stringify({ type: 'chat', text: 'Hello!' }));Why WebSocket is better than HTTP polling
| Approach | What it does | Downsides |
|---|---|---|
| Polling | the client makes a fetch() every X seconds | delays, extra requests |
| Long Polling | the client keeps a request "open" until a response | high load on the server |
| WebSocket | one persistent, two-way connection | harder to implement, needs a server with WS support |
Support
Works in all modern browsers
(Chrome, Firefox, Safari, Edge, Opera, Node.js)
and even in cloud functions and Web Workers.
Where WebSocket is used
- Chats and messengers (Telegram Web, Slack, Discord)
- Trading terminals and exchanges (real time)
- Online games
- Live notifications (push events)
- Collaborative document editing (Google Docs)
- Real-time geolocation tracking
Summary
| What | Description |
|---|---|
| Protocol type | Two-way, on top of TCP |
| URL scheme | ws:// or wss:// |
| Main difference from HTTP | A persistent connection and the ability to send data from both sides |
| Support | All modern browsers |
| Typical uses | Chats, online games, notifications, exchanges |
In summary:
WebSocket = a persistent, two-way, asynchronous communication channel between the browser and the server.
It keeps the connection open and lets data be exchanged in real time, without reloading the page and without constant HTTP requests.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.