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
- Setting Up the Project
-
Initialize a new Node.js project:
mkdir chat-app cd chat-app npm init -y
-
Install the necessary packages:
npm install express socket.io
-
Create the project structure:
mkdir public touch public/index.html touch server.js
- Creating the Server
- 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}`); });
- Creating the Front-End
- 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>
- Running the Application
-
Start the server:
node server.js
-
Open your browser and navigate to
http://localhost:3000
.
- Testing the Application
- Open multiple browser tabs and navigate to
http://localhost:3000
in each tab. - 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
-
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.
-
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.
-
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
-
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.
-
User Join/Leave Notifications:
- Emit
user joined
anduser left
events from the server. - Listen for these events on the front-end and display notifications.
- Emit
-
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
- Introduction to NPM
- Installing and Using Packages
- Creating and Publishing Packages
- Semantic Versioning
Module 6: Express.js Framework
- Introduction to Express.js
- Setting Up an Express Application
- Middleware
- Routing in Express
- Error Handling
Module 7: Databases and ORMs
- Introduction to Databases
- Using MongoDB with Mongoose
- Using SQL Databases with Sequelize
- CRUD Operations
Module 8: Authentication and Authorization
Module 9: Testing and Debugging
- Introduction to Testing
- Unit Testing with Mocha and Chai
- Integration Testing
- Debugging Node.js Applications
Module 10: Advanced Topics
Module 11: Deployment and DevOps
- Environment Variables
- Using PM2 for Process Management
- Deploying to Heroku
- Continuous Integration and Deployment