Skip to content
What is WebSocket — Simple Explanation with Examples

What is WebSocket — Simple Explanation with Examples

DodaTech Updated Jun 20, 2026 5 min read

WebSocket is a protocol that enables persistent, full-duplex communication between a client (typically a browser) and a server over a single TCP connection. Unlike HTTP’s request-response pattern, WebSocket allows either party to send data at any time.

What You’ll Learn

This article covers how WebSocket differs from HTTP polling, the handshake process, a working code example in JavaScript and Node.js, and real-world use cases. WebSocket powers real-time features in apps like Slack, Figma, and Google Docs.

The Problem WebSocket Solves

HTTP is a request-response protocol: the client sends a request, and the server sends a response. This works fine for loading web pages, but fails for real-time scenarios:

  • A chat app — when User B sends a message, User A’s browser needs to know immediately.
  • A stock ticker — prices change multiple times per second.
  • A collaborative document — one user’s edits must appear on other screens instantly.

With plain HTTP, developers tried polling: the client sends HTTP requests every few seconds asking “any updates?”. This wastes bandwidth, creates latency (worst case = poll interval), and puts unnecessary load on the server.

WebSocket solves this by establishing a persistent connection. Once open, either side can push messages freely with minimal overhead.

The Phone Call vs Letters Analogy

HTTP is like sending letters (postal mail):

  • You write a letter (request), mail it, and wait for a reply (response).
  • Each letter requires a new envelope, stamp, and trip to the post office.
  • To check for updates, you keep sending letters: “Any mail for me?” (polling).
  • Inefficient and slow for real-time conversation.

WebSocket is a phone call:

  • You dial (connect), the other person picks up (handshake).
  • Once connected, you both talk freely, back and forth, instantly.
  • The line stays open until someone hangs up.
  • No envelopes, no stamps, no polling.

How WebSocket Works: The Handshake

A WebSocket connection starts with an HTTP upgrade handshake, then switches to the WebSocket protocol.

1. Client sends upgrade request

GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13

2. Server responds with upgrade

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

After the 101 response, the connection upgrades. From this point, frames flow bidirectionally without HTTP headers overhead.

ws:// vs wss://

SchemeProtocolSecurity
ws://Unencrypted WebSocketPlain text
wss://WebSocket over TLSEncrypted (like HTTPS)

Always use wss:// in production. It provides encryption and avoids issues with proxies that block non-TLS connections.

Example: WebSocket Chat with Node.js and JavaScript

Server (Node.js with ws library)

import { WebSocketServer } from 'ws';

const wss = new WebSocketServer({ port: 8080 });

wss.on('connection', (ws) => {
  console.log('Client connected');

  // Send a welcome message to the connected client
  ws.send(JSON.stringify({
    type: 'system',
    message: 'Welcome to the chat!'
  }));

  // Broadcast incoming messages to all clients
  ws.on('message', (data) => {
    const message = data.toString();
    console.log(`Received: ${message}`);

    wss.clients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(JSON.stringify({
          type: 'chat',
          message,
          timestamp: new Date().toISOString()
        }));
      }
    });
  });

  ws.on('close', () => {
    console.log('Client disconnected');
  });
});

console.log('WebSocket server running on ws://localhost:8080');

Client (Browser JavaScript)

const ws = new WebSocket('ws://localhost:8080');

ws.onopen = () => {
  console.log('Connected to server');
  ws.send('Hello from the client!');
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log(`${data.type}: ${data.message}`);
  // Display in chat UI
};

ws.onclose = () => {
  console.log('Disconnected from server');
};

ws.onerror = (error) => {
  console.error('WebSocket error:', error);
};

// Send a message
function sendMessage(text) {
  if (ws.readyState === WebSocket.OPEN) {
    ws.send(text);
  }
}

Expected console output:

Connected to server
system: Welcome to the chat!
chat: Hello from the client!

Reconnection Handling

WebSocket connections can drop due to network issues. Production code should auto-reconnect:

function connect() {
  const ws = new WebSocket('wss://chat.example.com');

  ws.onclose = () => {
    console.log('Connection lost. Reconnecting in 3 seconds...');
    setTimeout(connect, 3000);
  };

  ws.onerror = () => {
    ws.close();
  };

  return ws;
}

const socket = connect();

Exponential backoff (1s, 2s, 4s, 8s…) is a more robust strategy to avoid overwhelming the server during an outage.

HTTP Polling vs WebSocket

AspectHTTP PollingWebSocket
LatencyInterval-based (e.g., 5s)Sub-second, real-time
OverheadFull HTTP headers per requestMinimal frame header (2 bytes)
Server loadHigh (constant new connections)Low (persistent connection)
DirectionClient-initiated onlyBidirectional
NetworkWorks through all proxiesRequires WS-aware proxies
Browser supportUniversalModern browsers (IE 10+)

Common Use Cases

  1. Chat applications — Slack, Discord, WhatsApp Web all use WebSocket for instant message delivery. Messages appear without refreshing or polling.

  2. Live notifications — Social media notifications, email alerts, and system monitoring dashboards push updates via WebSocket, replacing browser notification polling.

  3. Real-time gaming — Multiplayer browser games use WebSocket for low-latency state synchronization — player positions, scores, game events.

  4. Stock tickers and financial data — Trading platforms stream price updates via WebSocket. Latency measured in milliseconds matters for trading decisions.

  5. Collaborative editing — Google Docs, Figma, and Notion use WebSocket (or WebRTC) to sync edits between users in real time.

FAQ

What is the difference between WebSocket and HTTP/2 Server-Sent Events (SSE)? |
SSE is one-directional (server to client only) and works over standard HTTP. WebSocket is bidirectional. SSE is simpler for server push; WebSocket is better for interactive, bidirectional communication.
Is WebSocket secure? |
WebSocket itself does not provide encryption, but wss:// (WebSocket over TLS) encrypts the connection. Always use wss:// in production. WebSocket connections are subject to the same origin policy enforced by browsers.
Can WebSocket work through firewalls and proxies? |
Most modern firewalls and proxies handle WebSocket connections on port 443 (wss://). Some corporate proxies block WebSocket. The HTTP upgrade handshake helps negotiate the connection through compatible proxies.
What is Socket.IO? |
Socket.IO is a library that wraps WebSocket with additional features: auto-reconnection, fallback to HTTP long-polling (if WebSocket is unavailable), rooms/namespaces, and acknowledgements. It uses WebSocket when available.
How many concurrent WebSocket connections can a server handle? |
A single server can handle tens of thousands to hundreds of thousands of concurrent WebSocket connections, limited by file descriptors, memory, and CPU. Horizontal scaling with a pub/sub layer (Redis) supports millions.

Related Terms

What is an API — What is a REST API — What is GraphQL — What is a Microservice

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro