WebSockets and Real-Time Apps

2024-02-11

Most web applications use HTTP, which follows a request-response pattern. The client sends a request, the server responds, and the connection is closed. This works fine for most use cases, but it falls short when we need real-time updates. WebSockets solve this by keeping a persistent connection open between the client and server, allowing both sides to send data at any time.

How WebSockets Work

A WebSocket connection starts as a regular HTTP request with an upgrade header. The server agrees to the upgrade, and from that point the connection stays open. Both the client and the server can send messages to each other without waiting for a request. This is called full-duplex communication.

The handshake looks like a normal HTTP request but includes headers like Upgrade: websocket and Connection: Upgrade. Once the server responds with a 101 status code, the protocol switches from HTTP to WebSocket, and the persistent connection is established.

Using WebSockets in JavaScript

On the client side, the browser has a built-in WebSocket API:

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

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

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

socket.onclose = () => {
  console.log("Connection closed");
};

On the server side, libraries like ws for Node.js make it straightforward to handle WebSocket connections. We listen for connections, handle incoming messages, and broadcast to other connected clients.

Common Use Cases

Chat applications are the classic example. When one user sends a message, the server pushes it to all other connected users immediately, without them needing to refresh or poll the server.

Live dashboards and monitoring tools benefit from WebSockets as well. Instead of the client polling the server every few seconds for updated metrics, the server pushes new data as soon as it is available.

Collaborative editing, like what Google Docs does, relies on real-time communication to sync changes across multiple users editing the same document simultaneously.

When Not to Use WebSockets

WebSockets are not always the right choice. If the data updates infrequently, server-sent events (SSE) might be simpler. SSE is one-directional, from server to client, and uses regular HTTP. It is easier to set up and works well for things like notification feeds.

For applications where the client only needs data on demand, regular HTTP requests or polling at reasonable intervals are perfectly fine. WebSockets add complexity in terms of connection management, reconnection logic, and scaling, so we should only use them when the real-time requirement justifies it.