Skip to main content

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:

javascript
Client → Server: give me new data Server → Client: here is the data (connection closed)

WebSocket:

javascript
Client ↔ Server: connection established (once) From then on they communicate directly, without repeated requests

A 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)

  1. The client opens a connection:
javascript
GET /chat HTTP/1.1 Host: example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: <random-key> Sec-WebSocket-Version: 13
  1. The server responds:
javascript
HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: <hash-key>
  1. 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:

javascript
// 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:// - unencrypted
  • wss:// - a secure connection (over TLS)

How the server works (in Node.js)

An example with the ws library:

javascript
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:

javascript
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:

  • string
  • Blob
  • ArrayBuffer

You can even send JSON:

javascript
socket.send(JSON.stringify({ type: 'chat', text: 'Hello!' }));

Why WebSocket is better than HTTP polling

ApproachWhat it doesDownsides
Pollingthe client makes a fetch() every X secondsdelays, extra requests
Long Pollingthe client keeps a request "open" until a responsehigh load on the server
WebSocketone persistent, two-way connectionharder 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

WhatDescription
Protocol typeTwo-way, on top of TCP
URL schemews:// or wss://
Main difference from HTTPA persistent connection and the ability to send data from both sides
SupportAll modern browsers
Typical usesChats, 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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.