← JS Mastery | Module 8: Web APIs WebSockets & Real-Time Communication
Module 8

WebSockets & Real-Time Communication

⏱ 24 min read ● Advanced 🆓 Free

WebSocket Basics

HTTP is request-response. WebSocket is persistent and bidirectional — server can push data to client at any time. Essential for chat, live dashboards, collaborative apps, and games.

// Connect to WebSocket server:
const ws = new WebSocket("wss://example.com/ws");

ws.addEventListener("open", () => {
  console.log("Connected!");
  ws.send("Hello Server");
  ws.send(JSON.stringify({ type: "auth", token: "abc" }));
});

ws.addEventListener("message", (event) => {
  const data = JSON.parse(event.data);
  handleMessage(data);
});

ws.addEventListener("close", (event) => {
  console.log("Disconnected. Code:", event.code);
});

ws.addEventListener("error", (err) => {
  console.error("WS error:", err);
});

ws.close(1000, "Normal closure");

// ReadyState values:
// 0 = CONNECTING
// 1 = OPEN
// 2 = CLOSING
// 3 = CLOSED

Auto-Reconnect Client

class WebSocketClient {
  #url; #ws; #handlers = {}; #delay = 1000;
  
  constructor(url) {
    this.#url = url;
    this.#connect();
  }
  
  #connect() {
    this.#ws = new WebSocket(this.#url);
    
    this.#ws.onopen = () => {
      this.#delay = 1000;  // reset backoff
      this.#emit("connect");
    };
    
    this.#ws.onmessage = (e) => {
      try {
        const msg = JSON.parse(e.data);
        this.#emit("message", msg);
        this.#emit(msg.type, msg);
      } catch {}
    };
    
    this.#ws.onclose = () => {
      this.#emit("disconnect");
      setTimeout(() => this.#connect(), this.#delay);
      this.#delay = Math.min(this.#delay * 2, 30000); // exponential backoff
    };
  }
  
  send(data) {
    if (this.#ws.readyState === 1) {
      this.#ws.send(JSON.stringify(data));
    }
  }
  
  on(event, fn) {
    (this.#handlers[event] = this.#handlers[event] || []).push(fn);
    return this;
  }
  
  #emit(event, data) {
    (this.#handlers[event] || []).forEach(fn => fn(data));
  }
}

const ws = new WebSocketClient("wss://api.example.com/ws");
ws.on("connect", () => ws.send({ type: "subscribe", channel: "updates" }));
ws.on("update", data => updateUI(data));

⚡ Key Takeaways

🎯 Practice Exercises

EXERCISE 1

Build a chat UI using the WebSocketClient class above. Messages should show sender, content, and timestamp. Implement "is typing" indicators.

← Web Storage