Skip to content

Introduction to WebSocket

DodaTech Updated 2026-06-28 3 min read

In this tutorial, you will learn about Introduction to WebSocket. We cover key concepts, practical examples, and best practices to help you master this topic.

WebSocket is a protocol that enables full-duplex, bidirectional communication over a single TCP connection. Unlike HTTP request-response, WebSocket allows servers to push data to clients in real time.

What You'll Learn

  • What WebSocket is and how it works
  • How WebSocket differs from HTTP
  • Common use cases for WebSocket
  • WebSocket protocol overview
  • When to use WebSocket vs alternatives

Why It Matters

Users expect real-time experiences. WebSocket enables live updates, instant messaging, and real-time collaboration that traditional HTTP cannot efficiently provide.

Real-World Use

A financial trading platform uses WebSocket to stream real-time stock prices. Thousands of clients receive price updates within milliseconds of any market change, enabling split-second trading decisions.

Flow Chart

flowchart LR
    A[Client] -->|HTTP Upgrade Request| B[Server]
    B -->|101 Switching Protocols| A
    A <-->|Full-Duplex| B
    B -->|Push Data| A
    A -->|Send Data| B

Code Examples

Example 1: Basic WebSocket Client in JavaScript

const ws = new WebSocket('wss://echo.example.com');

ws.onopen = () => {
  console.log('Connected');
  ws.send('Hello Server!');
};

ws.onmessage = (event) => {
  console.log('Received:', event.data);
  ws.close();
};

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

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

Expected output: Client connects to server, sends a message, receives the echo response, and closes the connection.

Example 2: WebSocket Server in Node.js

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.toString());
    ws.send(`Echo: ${message}`);
  });

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

  ws.send('Welcome to the WebSocket server!');
});

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

Expected output: Server logs client connections, echoes messages back, and sends welcome message on connection.

Example 3: WebSocket vs HTTP Polling Comparison

// HTTP polling approach
async function pollForUpdates() {
  setInterval(async () => {
    const response = await fetch('/api/updates');
    const data = await response.json();
    console.log('Updates:', data);
  }, 2000);
}

// WebSocket approach
function connectWebSocket() {
  const ws = new WebSocket('wss://server.example.com/updates');
  ws.onmessage = (event) => {
    console.log('Real-time update:', event.data);
  };
}

Expected output: HTTP polling sends requests every 2 seconds even without updates. WebSocket delivers updates instantly only when data changes.

Common Mistakes

Mistake Explanation
Using HTTP for real-time features HTTP polling wastes bandwidth; use WebSocket for push-based communication
Ignoring connection lifecycle Always handle onopen, onmessage, onclose, and onerror events
Not handling reconnection Network interruptions happen; implement automatic reconnection
Mixing HTTP and WebSocket ports WebSocket often uses a different port or path than HTTP endpoints
Sending unformatted data Use JSON or a consistent Serialization format for all messages

Practice Questions

  1. What is the main difference between HTTP and WebSocket?
  2. How does a WebSocket connection start?
  3. What are common use cases for WebSocket?
  4. What happens when a WebSocket connection drops?
  5. How does WebSocket handle binary vs text data?

Challenge

Create a WebSocket echo server and client. The client should send 10 messages with 1-second intervals, receive echo responses, and log the round-trip time for each message. Include automatic reconnection if the server restarts.

FAQ

Is WebSocket part of HTTP?

WebSocket starts as an HTTP request (upgrade) but switches to its own protocol. It is not HTTP but uses HTTP for the initial handshake.

Can WebSocket work through firewalls?

WebSocket uses port 80 (ws) or 443 (wss), which are typically allowed through firewalls. WSS uses TLS encryption similar to HTTPS.

What is the maximum message size in WebSocket?

The WebSocket protocol supports messages up to 2^63 bytes, but practical limits depend on server and client implementations.

Does WebSocket support binary data?

Yes, WebSocket supports both text (UTF-8) and binary data frames. Use Blob or ArrayBuffer in JavaScript for binary data.

How many simultaneous WebSocket connections can a server handle?

This depends on server resources. A single Node.js server can handle 10,000+ concurrent connections with proper configuration.

Is WebSocket secure?

WebSocket Secure (WSS) uses TLS encryption, making it as secure as HTTPS. Always use WSS in production to prevent eavesdropping.

Mini Project

Build a real-time server monitoring dashboard. The server pushes CPU, memory, and disk usage metrics via WebSocket every second. The client displays live-updating charts showing system resource utilization.

What's Next

Learn about the WebSocket HTTP upgrade handshake

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro