Published on August 03, 2024By DeveloperBreeze

Building a Real-Time Chat Application with WebSockets in Node.js

In this tutorial, we will create a real-time chat application using Node.js and WebSockets. Real-time communication is a crucial aspect of modern web applications, allowing users to interact with each other instantaneously. By leveraging WebSockets, we can establish a persistent connection between the client and server, enabling seamless data exchange.

Node.js, WebSockets, real-time chat, web development, JavaScript, socket.io, Express.js, server-side, client-side, persistent connection, communication, data exchange, chat application

Introduction to WebSockets

WebSockets provide a full-duplex communication channel over a single TCP connection, allowing both the client and server to send messages at any time. Unlike HTTP, WebSockets maintain a persistent connection, making them ideal for applications requiring real-time updates, such as chat apps, online gaming, and live notifications.

Setting Up the Node.js Environment

Before we start building our chat application, we need to set up our Node.js environment. Follow these steps to get started:

Step 1: Install Node.js

If you haven’t already installed Node.js, you can download it from the [official website](https://nodejs.org/). Node.js includes npm, the package manager we will use to install dependencies.

Step 2: Create a Project Directory

Create a directory for your chat application project:

mkdir websocket_chat
cd websocket_chat

Step 3: Initialize a Node.js Project

Initialize a new Node.js project by creating a package.json file. This file will track your project’s dependencies and configurations.

npm init -y

Step 4: Install Required Packages

We will use the express framework for our server and socket.io for WebSocket functionality. Install these packages using npm:

npm install express socket.io

Building the Chat Application

Now that our environment is set up, we can start building our chat application.

Step 1: Create the Server

Create a file named server.js in your project directory and open it in your text editor. We will set up a basic Express server and integrate Socket.io.

const express = require('express');
const http = require('http');
const socketIo = require('socket.io');

// Initialize the Express app
const app = express();
const server = http.createServer(app);
const io = socketIo(server);

// Serve static files from the 'public' directory
app.use(express.static('public'));

// Handle a socket connection request from a client
io.on('connection', (socket) => {
    console.log('A user connected');

    // Listen for chat messages
    socket.on('chatMessage', (msg) => {
        io.emit('chatMessage', msg);
    });

    // Handle disconnection
    socket.on('disconnect', () => {
        console.log('User disconnected');
    });
});

// Start the server
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));

Step 2: Create the Client

Create a public directory in your project folder. This will contain the HTML, CSS, and JavaScript files for the client-side application.

Create index.html

Create an index.html file inside the public directory. This will be the main interface for our chat application.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Real-Time Chat</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="chat-container">
        <ul id="messages"></ul>
        <form id="chat-form">
            <input id="message" autocomplete="off" placeholder="Type a message" />
            <button type="submit">Send</button>
        </form>
    </div>
    <script src="/socket.io/socket.io.js"></script>
    <script src="main.js"></script>
</body>
</html>
Create styles.css

Create a styles.css file in the public directory to style our chat application.

body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f9;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
}

.chat-container {
    background-color: white;
    padding: 20px;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    width: 300px;
}

#messages {
    list-style-type: none;
    padding: 0;
    max-height: 300px;
    overflow-y: auto;
    margin-bottom: 10px;
}

#messages li {
    padding: 8px;
    background-color: #f1f1f1;
    border-radius: 3px;
    margin-bottom: 5px;
}

#chat-form {
    display: flex;
}

#message {
    flex: 1;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 3px;
    margin-right: 5px;
}

button {
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 3px;
    padding: 8px 12px;
    cursor: pointer;
}

button:hover {
    background-color: #0056b3;
}
Create main.js

Create a main.js file in the public directory to handle client-side Socket.io interactions.

const socket = io();

// DOM elements
const messageForm = document.getElementById('chat-form');
const messageInput = document.getElementById('message');
const messagesList = document.getElementById('messages');

// Handle form submission
messageForm.addEventListener('submit', (e) => {
    e.preventDefault();

    // Get the message from the input field
    const message = messageInput.value;

    // Emit the message to the server
    socket.emit('chatMessage', message);

    // Clear the input field
    messageInput.value = '';
});

// Listen for chat messages from the server
socket.on('chatMessage', (message) => {
    const li = document.createElement('li');
    li.textContent = message;
    messagesList.appendChild(li);
});

Running the Application

Now that we have set up both the server and client, we can run our chat application.

    • Start the Node.js server:

node server.js
   

    • Open your browser and navigate to http://localhost:3000/.

    • Open multiple tabs or browsers and start sending messages. You should see the messages appear in real-time across all clients.

Conclusion

In this tutorial, we built a real-time chat application using Node.js and WebSockets. We used Socket.io to establish a persistent connection between the client and server, allowing for real-time message exchange. This foundational knowledge can be extended to build more complex applications that require real-time communication, such as collaborative tools, online gaming, and live updates.

Comments

Please log in to leave a comment.

Continue Reading:

Simple WebSocket Server using 'ws' library

Published on January 26, 2024

javascript

File Stream Copy using 'fs' module

Published on January 26, 2024

javascript

Execute Shell Command using 'child_process' module

Published on January 26, 2024

javascript

Parse URL and Query Parameters

Published on January 26, 2024

javascript

Hashing Password with SHA-256 using 'crypto' module

Published on January 26, 2024

javascript

Create and Print Buffer

Published on January 26, 2024

javascript

Basic Authentication using 'express-basic-auth' middleware

Published on January 26, 2024

javascript

Construct File Path using 'path' module

Published on January 26, 2024

javascript

Event Emitter using 'events' module

Published on January 26, 2024

javascript

Set and Access Environment Variable

Published on January 26, 2024

javascript