After this lesson, you will be able to: Decide between WebSockets, polling, and Server-Sent Events; implement WebSockets with Socket.io.
Real-time features need the right transport. Each has a sweet spot.
WebSockets: bidirectional, persistent connection. Best for chat, multiplayer, live updates needing client→server. Server-Sent Events (SSE): one-way server→client over HTTP. Simpler; auto-reconnect built-in; works through proxies. Polling: client asks 'any updates?' every N seconds. Simplest; chattiest; fine for low-frequency updates.
Auto-fallback to polling if WS blocked.
// Server (Express + Socket.io)import { createServer } from "node:http";import { Server } from "socket.io";import express from "express";const app = express();const httpServer = createServer(app);const io = new Server(httpServer, { cors: { origin: "*" } });io.on("connection", (socket) => {socket.on("chat:send", (msg) => {io.emit("chat:received", { id: socket.id, msg });});});httpServer.listen(3000);// Client (browser)// import { io } from "socket.io-client";// const socket = io("http://localhost:3000");// socket.on("chat:received", (m) => console.log(m));// socket.emit("chat:send", "hello");
Built into the browser; no library needed.
app.get("/stream", (req, res) => {res.set({"Content-Type": "text/event-stream","Cache-Control": "no-cache","Connection": "keep-alive",});const interval = setInterval(() => {res.write(`data: ${JSON.stringify({ ts: Date.now() })}\n\n`);}, 1000);req.on("close", () => clearInterval(interval));});// Browser// const es = new EventSource("/stream");// es.onmessage = (e) => console.log(JSON.parse(e.data));
Chat / multiplayer / collaborative editing: WebSockets. Live updates / notifications / dashboards (server pushes; client doesn't need to send much): SSE. Low-frequency status checks: polling (with caching). Heavy scaling: WebSockets need sticky sessions / Redis pub/sub across nodes; SSE needs less coordination.
Pick the right transport.
Sign in and purchase access to unlock this lesson.