Building a Basic WebSocket Server with Node.js

A real-time chat application is an excellent example of how to utilize WebSocket with Node.js to create an interactive and engaging user experience. In this article, we will explore how to build a real-time chat application using WebSocket and Node.js.

Step 1: Setting Up the Environment

First, make sure you have Node.js installed on your computer. Create a new folder for your project and navigate into it using Terminal or Command Prompt.

Step 2: Installing the WebSocket Library

As before, use the "ws" library to install the WebSocket library:

npm install ws

Step 3: Building the WebSocket Server

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

// Import the WebSocket library
const WebSocket = require('ws');

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

// List of connections (clients)
const clients = new Set();

// Handle new connections
server.on('connection', (socket) => {
    console.log('Client connected.');

    // Add connection to the list
    clients.add(socket);

    // Handle incoming messages from the client
    socket.on('message', (message) => {
        // Send the message to all other connections
        for (const client of clients) {
            if (client !== socket) {
                client.send(message);
            }
        }
    });

    // Handle connection close
    socket.on('close', () => {
        console.log('Client disconnected.');
        // Remove the connection from the list
        clients.delete(socket);
    });
});

Step 4: Creating the User Interface (Client)

Create a file named index.html and write the following code:

<!DOCTYPE html>
<html>
<head>
    <title>Real-Time Chat</title>
</head>
<body>
    <input type="text" id="message" placeholder="Type a message">
    <button onclick="send()">Send</button>
    <div id="chat"></div>
    
    <script>
        const socket = new WebSocket('ws://localhost:8080');
        socket.onmessage = (event) => {
            const chat = document.getElementById('chat');
            chat.innerHTML += '<p>' + event.data + '</p>';
        };

        function send() {
            const messageInput = document.getElementById('message');
            const message = messageInput.value;
            socket.send(message);
            messageInput.value = '';
        }
    </script>
</body>
</html>

Step 5: Running the Server and Opening the Browser

In the Terminal, run the following command to start the WebSocket server:

node server.js

Open a web browser and navigate to "http://localhost:8080" to use the real-time chat application.

 

Conclusion

Congratulations! You have successfully built a real-time chat application using WebSocket and Node.js. This application allows users to interact and send/receive messages in real-time. You can continue to expand and customize this application to create various exciting features!