Skip to content

Introduction to WebSocket APIs

DodaTech Updated 2026-06-28 3 min read

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

WebSocket provides full-duplex communication over a single TCP connection. After an initial HTTP upgrade handshake, the client and server can send messages to each other at any time, enabling low-latency real-time applications.

What You'll Learn

  • WebSocket protocol fundamentals and lifecycle
  • The HTTP upgrade handshake Process
  • Use cases: chat, gaming, live feeds, collaborative editing
  • Comparing WebSocket to HTTP polling and Server-Sent Events

Why It Matters

WebSocket enables real-time features impossible with traditional HTTP. Latency drops from polling intervals (1-30s) to milliseconds. Major platforms like Slack, Discord, and Trello use WebSocket for real-time updates.

Real-World Use

Slack uses WebSocket for message delivery. Discord uses a WebSocket-based gateway for voice and chat. Financial trading platforms stream live prices via WebSocket. Google Docs uses WebSocket for collaborative editing.

flowchart LR
    Client[Client] -->|HTTP Upgrade Request| Server[Server]
    Server -->|101 Switching Protocols| Client
    Client <-->|Full-Duplex Messages| Server
    Client -->|Close Frame| Server
    Server -->|Close Frame| Client

Teacher Mindset

WebSocket is not HTTP, but it starts as HTTP. The upgrade handshake is a standard HTTP request with specific headers. After the handshake, the protocol switches to WebSocket frames over the same TCP connection.

Code Examples

// Example 1: Browser WebSocket client
const socket = new WebSocket('wss://api.example.com/chat');

socket.onopen = () => {
  console.log('Connected');
  socket.send(JSON.stringify({ type: 'join', room: 'general' }));
};

socket.onmessage = (event) => {
  const message = JSON.parse(event.data);
  console.log('Received:', message);
};

socket.onclose = () => console.log('Disconnected');
socket.onerror = (err) => console.error('Error:', err);
// Example 2: Server with ws library
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });

server.on('connection', (ws, req) => {
  console.log('Client connected from:', req.socket.remoteAddress);

  ws.on('message', (data) => {
    const message = JSON.parse(data);
    ws.send(JSON.stringify({ echo: message }));
  });

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

  ws.send(JSON.stringify({ type: 'welcome', message: 'Connected!' }));
});
# Example 3: Testing WebSocket with wscat
wscat -c ws://localhost:8080
Connected (press CTRL+C to quit)
> {"type": "ping"}
< {"type": "pong"}

Common Mistakes

  • Using WebSocket for request-response patterns that do not need real-time updates
  • Not handling reconnection and connection state management on the client
  • Sending plain text instead of structured JSON or binary messages
  • Forgetting to close connections properly, causing resource leaks
  • Not validating messages on the server before processing

Practice

  1. Open a WebSocket connection to a public test server (wss://echo.websocket.org).
  2. Send three messages and verify the echo responses.
  3. Implement a simple browser chat that connects to a WebSocket server.
  4. Handle connection drops with auto-reconnection logic.
  5. Challenge: Measure the latency difference between WebSocket and HTTP polling.

FAQ

What is the difference between WebSocket and HTTP?

WebSocket provides full-duplex communication over one connection. HTTP is half-duplex request-response. WebSocket has lower latency for real-time updates.

Can WebSocket work over HTTPS?

Yes. Secure WebSocket uses the wss:// scheme over TLS. This is required for production web applications.

What is the maximum message size in WebSocket?

The WebSocket protocol supports messages up to 2^63 bytes. Practical limits depend on server configuration and memory.

Does WebSocket support binary data?

Yes. WebSocket supports both text (UTF-8) and binary frames. Binary is more efficient for non-text data.

What browsers support WebSocket?

All modern browsers support WebSocket. The API is standardized by the W3C.

Mini Project

Build a minimal WebSocket chat server that accepts connections, broadcasts messages to all connected clients, and handles disconnection gracefully. Test with browser and command-line clients.

What's Next

Next, you will learn about the HTTP-to-WebSocket upgrade process in detail.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro