Internet of Things  

What is WebSocket and How It Works

Introduction

In today’s world, many web applications need real-time communication. For example, think of chat apps, online games, live sports updates, or stock trading dashboards. In such cases, waiting for the usual request-response process of HTTP feels too slow. That’s where WebSockets come in. WebSockets establish a direct and continuous connection between the client (such as a browser) and the server. This makes sending and receiving data faster and smoother.

What are WebSockets?

WebSockets are a communication protocol that allows two-way communication between a client and a server. Unlike normal HTTP, where the client always has to send a request first, WebSockets let both sides talk to each other freely at any time. This connection stays open until one side decides to close it.

In short

  • HTTP: one request, one response.

  • WebSocket: one connection, many messages both ways.

How WebSockets Work

Handshake Process

  • Everything starts with a handshake, which is like an agreement between the browser and the server.

  • The browser sends a special HTTP request asking to upgrade the connection to WebSocket.

  • If the server agrees, it replies with a confirmation.

  • From then on, the connection switches to WebSocket mode.

Persistent Connection

  • After the handshake, the connection stays open and active.

  • The client and server can send messages at any time without waiting for a request.

Message Frames

  • Data is sent in frames (small data packets).

  • Frames can contain text, binary data, or control messages, such as pings, to check if the connection is alive.

  • This method is much faster and lighter compared to HTTP requests.

Key Features of WebSockets

  • Two-way communication: Both the client and server can send messages independently.

  • Always connected: The connection stays alive until closed.

  • Low latency: Data moves faster because there’s no need to reopen connections repeatedly.

  • Lightweight: Uses fewer headers and less overhead compared to HTTP.

  • Broad support: Works in most modern browsers and frameworks.

Benefits of Using WebSockets

  1. Real-Time Updates: Perfect for chat apps, stock prices, live scores, or notifications.

  2. Efficiency: Reduces unnecessary requests, saving bandwidth and processing power.

  3. Scalability: Can handle thousands of users connected at the same time.

  4. Lower Server Load: No repeated requests means less pressure on servers.

  5. Better User Experience: Faster responses make apps feel smoother and more interactive.

Everyday Use Cases of WebSockets

  • Chat Applications: Apps like Slack, WhatsApp Web, or Messenger utilize WebSockets.

  • Live Sports Scores: Updates come instantly as the game progresses.

  • Stock Market Apps: Prices change in real time without refreshing the page.

  • Online Gaming: Multiplayer games utilize WebSockets for rapid player interactions.

  • Collaborative Tools: Apps like Google Docs require real-time syncing.

  • IoT Devices: Devices send and receive updates instantly via WebSockets.

Example. WebSocket

  
    // Create a WebSocket connection
const socket = new WebSocket("ws://example.com/socket");

// When connection opens
socket.addEventListener("open", () => {
  console.log("Connected to server");
  socket.send("Hello from client!");
});

// When a message is received
socket.addEventListener("message", (event) => {
  console.log("Message from server:", event.data);
});

// When connection closes
socket.addEventListener("close", () => {
  console.log("Connection closed");
});
  

Limitations of WebSockets

  • Firewall/Proxy Issues: Some networks may block WebSocket connections.

  • Server Resources: Keeping thousands of connections open uses more memory.

  • Older Browser Support: Some ancient browsers may not support WebSockets.

  • Security Risks: Unsecured connections (ws://) can be attacked; therefore, wss:// (Secure WebSockets) should be used.

Summary

WebSockets are a modern way of enabling real-time, two-way communication between clients and servers. Unlike traditional HTTP, they keep the connection open and allow instant data exchange. This makes them ideal for apps that need fast updates, like chat apps, online games, and stock dashboards. While they have some limitations, the benefits of speed, efficiency, and user experience make WebSockets an essential technology in modern web development.