Creating a Real-Time Chat Application with Node.js
A real-time chat application allows users to exchange messages instantly using technologies like WebSockets and Socket.IO. Here's a step-by-step guide:
1. Project Setup
Initialize the Project
- Bi-directional communication (client ↔ server).
- Reduced latency compared to HTTP requests.
- Low overhead with minimal protocol framing.
- Suitable for applications requiring real-time updates, like chat apps or live dashboards.
mkdir chat-app
cd chat-app
npm init -y
npm install express socket.io
2. Server-Side Implementation
Create server.js
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html'); // Serve the front-end
});
// Handle real-time connections
io.on('connection', (socket) => {
console.log('A user connected');
// Receive and broadcast messages
socket.on('chat message', (msg) => {
io.emit('chat message', msg); // Send message to all clients
});
socket.on('disconnect', () => {
console.log('User disconnected');
});
});
server.listen(3000, () => console.log('Server running on http://localhost:3000'));
3. Front-End Implementation
Create index.html
Chat App
Real-Time Chat
4. Running the Application
Start the server:
node server.js
http://localhost:3000
.