,

Building a Real-Time Chat Application with WebSockets using ExpressJS

Posted by






Creating a Chat Application with WebSockets using ExpressJS

Creating a Chat Application with WebSockets using ExpressJS

WebSockets are a powerful tool for building real-time web applications, and ExpressJS is a popular web framework for Node.js. In this article, we’ll walk through the process of creating a chat application using WebSockets and ExpressJS.

Setting up the Project

Before we dive into the code, make sure you have Node.js and npm installed on your machine. Create a new directory for your project and run the following command to initialize a new Node.js project:

    
      npm init -y
    
  

Next, install ExpressJS and the ws (WebSocket) package using npm:

    
      npm install express ws
    
  

Creating the Server

Now that we have our dependencies installed, let’s create a new file called server.js and import the necessary modules:

    
      const express = require('express');
      const http = require('http');
      const WebSocket = require('ws');
      const app = express();
      const server = http.createServer(app);
      const wss = new WebSocket.Server({ server });
    
  

We’ve created an Express app and a WebSocket server using the ws package. Now, let’s set up a WebSocket connection listener and handle incoming messages:

    
      wss.on('connection', function connection(ws) {
        ws.on('message', function incoming(message) {
          // Broadcast the message to all connected clients
          wss.clients.forEach(function each(client) {
            if (client !== ws && client.readyState === WebSocket.OPEN) {
              client.send(message);
            }
          });
        });
      });
    
  

Creating the Client

Next, let’s create a basic HTML file for the chat application. Save the following code as index.html:

    
      <!DOCTYPE html>
      <html>
      <head>
        <title>WebSocket Chat</title>
      </head>
      <body>
        <ul id="messages"></ul>
        <input id="message" autocomplete="off" /><button onclick="sendMessage()">Send</button>
        <script>
          const socket = new WebSocket('ws://localhost:3000');
          socket.onmessage = function(event) {
            const messages = document.getElementById('messages');
            const message = document.createElement('li');
            const text = document.createTextNode(event.data);
            message.appendChild(text);
            messages.appendChild(message);
          };
          function sendMessage() {
            const input = document.getElementById('message');
            socket.send(input.value);
            input.value = '';
          }
        </script>
      </body>
      </html>
    
  

This HTML file sets up a WebSocket connection to the server and provides a simple interface for sending and receiving chat messages.

Running the Application

Finally, start the Express server by adding the following code to the end of server.js:

    
      server.listen(3000, function() {
        console.log('Server is listening on port 3000');
      });
    
  

Now run the server using the following command:

    
      node server.js
    
  

Open your web browser and navigate to http://localhost:3000. You should see the chat interface, and you can start sending messages to see them appear in real-time on other connected clients.

Congratulations! You’ve successfully created a chat application using WebSockets and ExpressJS. With this foundation, you can expand the functionality and design of your chat application to fit your needs.


0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Quiggly Childree
7 months ago

😚 promosm