In this module, we will build a real-time chat application using Node.js and Socket.io. This project will help you understand how to create a server that can handle real-time communication between clients.

Objectives

  • Understand the basics of real-time communication.
  • Set up a Node.js server with Socket.io.
  • Create a simple front-end to interact with the server.
  • Implement real-time messaging between clients.

Prerequisites

Before starting this module, make sure you have:

  • Basic knowledge of Node.js and Express.js.
  • Familiarity with HTML, CSS, and JavaScript.
  • Installed Node.js and npm on your machine.

Step-by-Step Guide

  1. Setting Up the Project

  1. Initialize a new Node.js project:

    mkdir chat-app
    cd chat-app
    npm init -y
    
  2. Install the necessary packages:

    npm install express socket.io
    
  3. Create the project structure:

    mkdir public
    touch public/index.html
    touch server.js
    

  1. Creating the Server

  1. Set up the Express server in server.js:
    const express = require('express');
    const http = require('http');
    const socketIo = require('socket.io');
    
    const app = express();
    const server = http.createServer(app);
    const io = socketIo(server);
    
    app.use(express.static('public'));
    
    io.on('connection', (socket) => {
        console.log('A user connected');
        socket.on('disconnect', () => {
            console.log('User disconnected');
        });
        socket.on('chat message', (msg) => {
            io.emit('chat message', msg);
        });
    });
    
    const PORT = process.env.PORT || 3000;
    server.listen(PORT, () => {
        console.log(`Server is running on port ${PORT}`);
    });
    

  1. Creating the Front-End

  1. Set up the HTML structure in public/index.html:
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Chat App</title>
        <style>
            body { font-family: Arial, sans-serif; }
            #messages { list-style-type: none; padding: 0; }
            #messages li { padding: 8px; margin-bottom: 10px; background: #f4f4f4; }
            #form { display: flex; }
            #input { flex: 1; padding: 10px; }
            #send { padding: 10px; }
        </style>
    </head>
    <body>
        <ul id="messages"></ul>
        <form id="form" action="">
            <input id="input" autocomplete="off" /><button id="send">Send</button>
        </form>
        <script src="/socket.io/socket.io.js"></script>
        <script>
            const socket = io();
            const form = document.getElementById('form');
            const input = document.getElementById('input');
            const messages = document.getElementById('messages');
    
            form.addEventListener('submit', (e) => {
                e.preventDefault();
                if (input.value) {
                    socket.emit('chat message', input.value);
                    input.value = '';
                }
            });
    
            socket.on('chat message', (msg) => {
                const item = document.createElement('li');
                item.textContent = msg;
                messages.appendChild(item);
                window.scrollTo(0, document.body.scrollHeight);
            });
        </script>
    </body>
    </html>
    

  1. Running the Application

  1. Start the server:

    node server.js
    
  2. Open your browser and navigate to http://localhost:3000.

  1. Testing the Application

  1. Open multiple browser tabs and navigate to http://localhost:3000 in each tab.
  2. Send messages from one tab and see them appear in real-time in all other tabs.

Summary

In this module, you learned how to build a simple real-time chat application using Node.js and Socket.io. You set up a Node.js server, created a front-end to interact with the server, and implemented real-time messaging between clients. This project demonstrates the power of real-time communication and how easily it can be implemented with Node.js and Socket.io.

Exercises

  1. Enhance the chat application by adding user names.

    • Modify the front-end to prompt users for their names.
    • Display the user names along with the messages.
  2. Add a feature to notify users when someone joins or leaves the chat.

    • Emit events when users connect and disconnect.
    • Display notifications in the chat window.
  3. Implement a feature to show the list of online users.

    • Maintain a list of connected users on the server.
    • Update the list in real-time on the front-end.

Solutions

  1. Adding User Names:

    • Modify the front-end to prompt for user names and include them in the messages.
    • Update the server to handle user names.
  2. User Join/Leave Notifications:

    • Emit user joined and user left events from the server.
    • Listen for these events on the front-end and display notifications.
  3. Online Users List:

    • Maintain a list of connected users on the server.
    • Emit the updated list to all clients whenever a user connects or disconnects.
    • Display the list on the front-end.

By completing these exercises, you will gain a deeper understanding of real-time communication and how to enhance a chat application with additional features.

Node.js Course

Module 1: Introduction to Node.js

Module 2: Core Concepts

Module 3: File System and I/O

Module 4: HTTP and Web Servers

Module 5: NPM and Package Management

Module 6: Express.js Framework

Module 7: Databases and ORMs

Module 8: Authentication and Authorization

Module 9: Testing and Debugging

Module 10: Advanced Topics

Module 11: Deployment and DevOps

Module 12: Real-World Projects

© Copyright 2024. All rights reserved