In this article we will learn how we can create chat application using socket.io through which we can connect to the end users and chat with them using four digit authentication code, this is fully build small chat application through which you can learn how socket.io works. In this project we have used node.js as a server and simple html as client side. So lets learn about what is socket.io chat application is.
This is socket io chat application a real-time chat app on which we will learn how we can Broadcast messages with Socket.IO hrough Socket.IO events lets learn how we can build Node.js chat application
Socket.io Chat Application
simple-chat-application-using-node-js-and-socket-io
The Socket.IO chat application is a real-time messaging platform built with Node.js and Socket.IO, designed to facilitate instant communication between users. At its core, this application leverages the power of WebSockets through Socket.IO to provide a seamless chat experience, where messages are transmitted in real time without the need for page reloads. Node.js chat application
build a simple chat app with node.js and socket.io
So previously we need a page reload to get messages and notifications in out applications , but due to socket.io we communicate on real time with the users
Lets go through some key features of real time chat applications
The application presents a straightforward and intuitive user interface. Users input a 4-digit code to join a chat room and then send and receive messages in a dedicated chat area. This simplicity ensures ease of use for all participants.
chat application node.js socket.io
The chat interface dynamically updates to display incoming messages and notify users when new participants join a room. This feature keeps all participants informed and engaged throughout their interactions.
While the application can be expanded with a backend for persistent data storage or additional features, the core functionality operates seamlessly with just the frontend and Socket.IO integration. This makes it ideal for quick setups and demonstrations.
So lets proceeds to the coding sections of this small chat application, below is the node.js server side implementation
Package.json
{
"name": "chat-app",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"express": "^4.18.2",
"socket.io": "^4.5.1"
}
}
Server.js
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const path = require('path');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
const PORT = process.env.PORT || 3000;
app.use(express.static('public'));
io.on('connection', (socket) => {
console.log('New client connected');
socket.on('joinRoom', (code) => {
socket.join(code);
console.log(`Client joined room: ${code}`);
io.to(code).emit('message', 'A new user has joined the room');
});
socket.on('chatMessage', ({ code, message }) => {
io.to(code).emit('message', message);
});
socket.on('disconnect', () => {
console.log('Client disconnected');
});
});
app.use(express.static(path.join(__dirname, 'pages')));
server.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Static 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;
}
#chat {
margin-top: 20px;
}
.message {
margin-bottom: 10px;
}
</style>
</head>
<body>
<h1>Chat Application</h1>
<div>
<input id="code" type="text" placeholder="Enter 4-digit code" />
<button onclick="joinRoom()">Join Room</button>
</div>
<div id="chat" style="display: none">
<input id="message" type="text" placeholder="Type a message" />
<button onclick="sendMessage()">Send</button>
<div id="messages"></div>
</div>
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
function joinRoom() {
const code = document.getElementById('code').value;
if (code.length === 4) {
socket.emit('joinRoom', code);
document.getElementById('chat').style.display = 'block';
} else {
alert('Please enter a 4-digit code.');
}
}
function sendMessage() {
const code = document.getElementById('code').value;
const message = document.getElementById('message').value;
socket.emit('chatMessage', { code, message });
document.getElementById('message').value = '';
}
socket.on('message', (msg) => {
const messages = document.getElementById('messages');
const messageElement = document.createElement('div');
messageElement.className = 'message';
messageElement.textContent = msg;
messages.appendChild(messageElement);
});
</script>
</body>
</html>
Steps to install your application
Initialize a Node.js Project
Open your terminal or command prompt and create a new directory for your project, then initialize it with npm:
bashCopy codemkdir my-static-site
cd my-static-site
npm init -y
Install Express
Install the Express library:
bashCopy codenpm install express
You can also visit the stack Blitz project where your can directly run my code and test it on live
Stack Blitz
https://stackblitz.com/~/github.com/mohit49/socket.io-chat-application
Git Hub
https://github.com/mohit49/socket.io-chat-application?tab=readme-ov-file