DEV Community

Arhan Khan
Arhan Khan

Posted on

WebSockets for Beginners: Real-Time Data Without Refreshing

WebSockets are how the web does real time. Chat apps, live scores, stock tickers, and multiplayer games all use them. The problem they solve is simple: normal HTTP means the browser asks and the server answers. WebSockets keep one connection open so the server can push new data the moment it exists — no refreshing, no polling.

On the client, the API is tiny:

const socket = new WebSocket("wss://example.com/live");

socket.onopen = () => {
  socket.send(JSON.stringify({ type: "join", room: "general" }));
};

socket.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log("New message:", data);
};
Enter fullscreen mode Exit fullscreen mode

On the server, Node.js with the ws library looks like this:

import { WebSocketServer } from "ws";

const wss = new WebSocketServer({ port: 8080 });

wss.on("connection", (socket) => {
  socket.on("message", (message) => {
    // Send the message to everyone connected
    wss.clients.forEach((client) => client.send(message.toString()));
  });
});
Enter fullscreen mode Exit fullscreen mode

That is a working group chat in about fifteen lines. Every client that connects gets every message instantly.

WebSockets also have a cousin you should know about: Server-Sent Events. SSE is simpler and works over plain HTTP, but data only flows one way — server to browser. If users need to send data back, like typing in a chat, WebSockets are the right tool.

Who is it for? Anyone building live features: chats, notifications, collaborative editors, dashboards, or games. If your app polls an API every few seconds, WebSockets will almost always be the better design.

The limits: connections stay open, so your server holds more memory per user than with plain HTTP. Scaling needs care — when you run multiple servers, they have to share messages between themselves, usually through a tool like Redis. And some corporate firewalls block WebSocket connections, so always have a fallback plan.

Start today: build the tiny chat server above, open it in two browser tabs, and watch a message typed in one tab appear in the other instantly. That moment is the whole point of WebSockets.

Top comments (0)