Real-Time Web Applications with Node.js and WebSockets (Intermediate)

Real-Time Web Applications with Node.js and WebSockets (Intermediate)
Written by
Wilco team
November 13, 2024
Tags
No items found.
Real-Time Web Applications with Node.js and WebSockets

Real-Time Web Applications with Node.js and WebSockets

In this guide, we will explore the powerful combination of Node.js and WebSockets for developing real-time web applications. We will delve into the fundamentals of WebSocket protocol, how it differs from traditional HTTP requests, and how to set up a Node.js server to handle WebSocket connections. By the end of this post, you will have built a simple chat application that exemplifies real-time communication between multiple users.

Understanding the WebSocket Protocol

WebSocket is a communication protocol that provides full-duplex communication between the client and the server over a single, long-lived connection. Unlike traditional HTTP requests, which are unidirectional and require a new connection for each request, WebSocket connections allow bidirectional communication, making them perfect for real-time applications.

Setting Up a Node.js Server to Handle WebSocket Connections

We will use the popular Node.js library ws to handle WebSocket connections on our server. To install it, run the following command in your terminal:

npm install ws

Next, we will create a simple WebSocket server that listens for connections and messages from clients.


    // Importing the ws module
    const WebSocket = require('ws');

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

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

        // Handling message event
        ws.on('message', (message) => {
            console.log('Received:', message);
        });

        // Sending a message to the client
        ws.send('Hello from server!');
    });
    

Building a Basic Chat Application

Now that we have set up our WebSocket server, we can start building our chat application. We will create a simple HTML page with a text input and a button for sending messages, and a div element for displaying received messages.

HTML Structure


    <html>
    <body>
        <div id="messages"></div>
        <input id="message-input" type="text">
        <button id="send-button">Send</button>
    </body>
    </html>
    

Client-Side JavaScript

On the client side, we will open a WebSocket connection to our server and handle the sending and receiving of messages.


    // Opening a WebSocket connection
    const ws = new WebSocket('ws://localhost:8080');

    // Getting references to HTML elements
    const messagesDiv = document.getElementById('messages');
    const messageInput = document.getElementById('message-input');
    const sendButton = document.getElementById('send-button');

    // Handling open event
    ws.onopen = () => {
        console.log('Connected to server');
    };

    // Handling message event
    ws.onmessage = (event) => {
        const message = event.data;
        messagesDiv.innerHTML += '<p>' + message + '</p>';
    };

    // Sending a message to the server
    sendButton.onclick = () => {
        const message = messageInput.value;
        ws.send(message);
        messageInput.value = '';
    };
    

Top 10 Key Takeaways

  1. WebSocket is a protocol that enables full-duplex communication between a client and a server.
  2. WebSocket differs from HTTP as it allows bidirectional communication over a single, long-lived connection.
  3. You can use the ws module in Node.js to handle WebSocket connections and messages.
  4. You can set up a WebSocket server using ws and Node.js that can listen for connections and messages from clients.
  5. Real-time web applications can be built using Node.js and WebSockets.
  6. WebSocket connections facilitate real-time communication in web applications.
  7. WebSocket connections are ideal for applications that require instant data updates.
  8. Building a simple chat application helps understand the concept of real-time communication with WebSockets.
  9. On the client side, a WebSocket connection can be opened and messages can be sent and received.
  10. For real-time web applications, WebSockets and Node.js provide a powerful and efficient solution.

Ready to start learning? Start the quest now

Other posts on our blog
No items found.