Implementing WebSockets for Real-Time Communication in Node.js

In this guide, we will explore how to implement WebSockets in Node.js to enable real-time communication between clients and servers. You'll learn the basics of WebSockets, how to set them up, and see practical code examples to get you started.
By Jamie

Understanding WebSockets

WebSockets provide a full-duplex communication channel over a single TCP connection. This technology is particularly useful in applications that require real-time data updates, such as chat applications, live notifications, and online gaming.

Setting Up a Simple WebSocket Server

To start using WebSockets in Node.js, we will use the ws library, which is a popular WebSocket implementation. Follow these steps to create a simple WebSocket server:

Step 1: Install the ws Library

First, ensure you have Node.js installed on your machine. Then, create a new directory for your project and initialize a new Node.js application:

mkdir websocket-example
cd websocket-example
npm init -y

Now, install the ws library:

npm install ws

Step 2: Create the WebSocket Server

Create a file named server.js and add the following code:

const WebSocket = require('ws');

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

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

    // Send a welcome message to the newly connected client
    ws.send('Welcome to the WebSocket server!');

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

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

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

Step 3: Running the Server

Run your WebSocket server using:

node server.js

You should see the message indicating that the server is running.

Creating a WebSocket Client

To test our WebSocket server, we can create a simple HTML client. Create a file named index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket Client</title>
</head>
<body>
    <h1>WebSocket Client</h1>
    <input type="text" id="messageInput" placeholder="Type a message..."><br>
    <button id="sendButton">Send</button>
    <div id="messages"></div>

    <script>
        const ws = new WebSocket('ws://localhost:8080');

        ws.onopen = () => {
            console.log('Connected to the server');
        };

        ws.onmessage = (event) => {
            const messagesDiv = document.getElementById('messages');
            messagesDiv.innerHTML += `<p>${event.data}</p>`;
        };

        document.getElementById('sendButton').onclick = () => {
            const input = document.getElementById('messageInput');
            ws.send(input.value);
            input.value = '';
        };
    </script>
</body>
</html>

Step 4: Testing the Client

Open index.html in a web browser. Type a message into the input field and click the