DEV Community

Cover image for Understanding WebSocket: Real-Time Communication Made Easy
Joseph Giwa
Joseph Giwa

Posted on

Understanding WebSocket: Real-Time Communication Made Easy

A Simple Analogy

Imagine you are at a restaurant and place an order. In a traditional setup [like HTTP requests], you call the waiter over, place your order, and then wait. If you want an update on your food, you have to keep waving them down and asking, "Is my food ready yet?"

Now, imagine a different approach—when you order, the waiter gives you a small pager. Instead of you having to ask repeatedly, the pager buzzes the moment your food is ready. This is how WebSocket works—once a connection is established, the server can push updates to the client in real-time, without the client having to check back constantly.


What is WebSocket?

WebSocket is a full-duplex communication protocol that allows real-time data exchange between a client [e.g., browser] and a server over a persistent connection. Unlike traditional HTTP, where the client must request updates, WebSocket allows the server to push updates instantly when new data is available.


Practical Use Cases

  • Chat Applications: Instant messaging platforms rely on WebSocket for real-time message delivery. [e.g., WhatsApp, Slack, Messenger]
  • Live Notifications: Updates like stock prices, sports scores, or breaking news leverage WebSocket for instant alerts.
  • Multiplayer Games: Real-time interactions between players depend on WebSocket’s low-latency communication.
  • Collaborative Tools: Tools like shared documents or whiteboards use WebSocket to synchronize changes instantly among users. [e.g., Google Docs, whiteboards, live code editors]

The Chatbot on Send247's website is another solid example.

Send247 facilitates fast, reliable, and affordable door-to-door deliveries for individuals and businesses across select areas in London.

[Demo] user interacting with the Chatbot to book a delivery request.


Setting Up WebSocket in Node.js

Let’s implement a basic WebSocket server using Node.js with the ws package.

Step 1: Install Dependencies

To get started, install the ws library, which provides WebSocket support in Node.js.

npm install ws
Enter fullscreen mode Exit fullscreen mode

Step 2: Create a WebSocket Server

This simple WebSocket server listens for incoming connections and messages:

const WebSocket = require('ws');

// Create a WebSocket server on port 8080
const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', (ws) => {
    console.log('New client connected');

    // Send a welcome message when a client connects
    ws.send(JSON.stringify({ message: 'Welcome to WebSocket Server!' }));

    // Listen for messages from the client
    ws.on('message', (message) => {
        console.log(`Received: ${message}`);

        // Broadcast message to all connected clients
        wss.clients.forEach(client => {
            if (client.readyState === WebSocket.OPEN) {
                client.send(`Echo: ${message}`);
            }
        });
    });

    // Handle client disconnection
    ws.on('close', () => {
        console.log('Client disconnected');
    });
});

console.log('WebSocket server is running on ws://localhost:8080');
Enter fullscreen mode Exit fullscreen mode

This simple WebSocket server:

  • accepts new client connections
  • sends a welcome message to each client
  • listens for messages from clients and echoes them back
  • broadcasts messages to all connected clients

Creating a WebSocket Client (Browser)

To connect to the WebSocket server from a web page, you can use the built-in WebSocket API in JavaScript:

const socket = new WebSocket('ws://localhost:8080');

// Listen for messages from the server
socket.onmessage = (event) => {
    console.log('Server says:', event.data);
};

// Send a message to the server
socket.onopen = () => {
    console.log('Connected to WebSocket server');
    socket.send('Hello, WebSocket Server!');
};

// Handle connection close
socket.onclose = () => {
    console.log('Disconnected from WebSocket server');
};
Enter fullscreen mode Exit fullscreen mode

Enhancing the WebSocket Server: Real-Time Notifications

Let’s modify the server to send periodic real-time updates [e.g., stock price updates].

setInterval(() => {
    const stockPrice = (Math.random() * 100).toFixed(2); // Generate a random stock price

    wss.clients.forEach(client => {
        if (client.readyState === WebSocket.OPEN) {
            client.send(JSON.stringify({ stock: `AAPL: $${stockPrice}` }));
        }
    });
}, 5000); // Send updates every 5 seconds
Enter fullscreen mode Exit fullscreen mode

Now, all connected clients receive real-time stock price updates every 5 seconds.


Conclusion

Whether you are developing a chat app, live notifications, multiplayer games, or collaborative tools, WebSocket enables seamless, efficient, and interactive user experiences. By reducing latency and optimizing resource usage, it powers modern applications that demand real-time engagement.

If you are looking to enhance your web application with instant communication, WebSocket is the technology to consider. Now that you have a working knowledge of how it functions, it’s time to explore its full potential in your own projects!

Top comments (3)

Collapse
 
mahmud-r-farhan profile image
Mahmudur Rahman • Edited

"Great insights on WebSocket! If anyone interested in a practical application, check out my post on building a Real-Time Location Tracker using WebSockets, Leaflet, and WebRTC: Link. Looking forward to your thoughts!"

Collapse
 
panindrakumar profile image
Panindra Kumar

Thank you for sharing a detailed explanation🙌🙌🙌

Collapse
 
tobidelly profile image
TD!

Nice one