Creating a Real-Time Chat Application with Node.js and Socket.io
Learn how to create a real-time chat application using Node.js and Socket.io, and understand the basics of real-time communication.
Introduction to Socket.io
Socket.io is a JavaScript library that enables real-time communication between clients and servers. To use Socket.io with Node.js, you need to install the socket.io package. Run the following command in your terminal:
npm install socket.io
Step 1: Create a New Node.js Project
Create a new directory for your project and navigate to it in your terminal. Then, run the following command to create a new npm project:
npm init -y
Step 2: Install Required Packages
Install the required packages:
npm install express socket.io
Step 3: Create a New Express App
Create a new file called app.js and add the following code to it:
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
app.use(express.static('public'));
let messages = [];
io.on('connection', (socket) => {
console.log('Client connected');
socket.emit('messages', messages);
socket.on('new-message', (data) => {
messages.push(data);
io.sockets.emit('messages', messages);
});
});
server.listen(3000, () => {
console.log('Server started on port 3000');
});
Step 4: Create a New HTML File
Create a new HTML file called index.html in the public directory:
<!DOCTYPE html>
<html>
<head>
<title>Chat Application</title>
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
socket.on('messages', (messages) => {
const chatBox = document.getElementById('chat-box');
chatBox.innerHTML = '';
messages.forEach((message) => {
const paragraph = document.createElement('p');
paragraph.textContent = message;
chatBox.appendChild(paragraph);
});
});
document.getElementById('send-button').addEventListener('click', () => {
const message = document.getElementById('message-input').value;
socket.emit(, message);
.(). = ;
});
Chat Application
Send
You can now start the server by running the following command in your terminal:
node app.js
Open two web browsers and navigate to http://localhost:3000 to test the chat application.