HTTP is requestโresponseโgoodbye. Chat, live scores and collaborative editors need the server to push โ that is WebSockets: one connection, both directions, always on.
Polling vs WebSocket
- Polling: "anything new?" every 3s โ wasteful, laggy, but dead simple
- WebSocket: persistent connection; server pushes the instant something happens
Browser side โ built in
const ws = new WebSocket("wss://example.com/chat");
ws.onmessage = (e) => addMessage(JSON.parse(e.data));
ws.send(JSON.stringify({ text: "Hi!" }));Server side โ Node + ws
import { WebSocketServer } from "ws";
const wss = new WebSocketServer({ port: 8080 });
wss.on("connection", (socket) => {
socket.on("message", (msg) => {
// broadcast to everyone
wss.clients.forEach(c => c.readyState === 1 && c.send(msg));
});
});Why people use Socket.io instead
Raw WebSockets don't reconnect after network drops, have no rooms/namespaces, and no fallbacks. Socket.io adds all three โ worth it for real projects.
A chat app is a top-tier portfolio project: it proves async, events and state handling in one demo.