In this tutorial, we will walk through the process of building a real-time chat application using Express.js and Socket.IO. Socket.IO is a JavaScript library that enables real-time, bidirectional and event-based communication between the browser and the server. Express.js is a fast and minimal web application framework for Node.js.
Prerequisites
Before we start, make sure you have the following prerequisites installed on your machine:
- Node.js and npm
- Express.js
- Socket.IO
Setting up the project
- Create a new directory for your project and navigate into it:
$ mkdir chat-app
$ cd chat-app
- Initialize a new Node.js project:
$ npm init -y
- Install Express.js and Socket.IO:
$ npm install express socket.io
Creating the server
-
Create a new file named
server.js
and open it in your preferred code editor. -
Import the required packages:
const express = require('express');
const http = require('http');
const socketIO = require('socket.io');
- Create an Express.js app and a server instance:
const app = express();
const server = http.createServer(app);
const io = socketIO(server);
- Set up the server to listen on a specific port:
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Adding real-time chat functionality with Socket.IO
- Inside the
io.on('connection', (socket) => {})
event listener, handle themessage
event when a new message is received:
io.on('connection', (socket) => {
socket.on('message', (data) => {
// Handle the received message
});
});
- Emit the
message
event to all connected clients when a new message is received:
io.on('connection', (socket) => {
socket.on('message', (data) => {
io.emit('message', data);
});
});
- Handle the
message
event on the client-side using JavaScript:
const socket = io();
socket.on('message', (data) => {
// Handle the received message
});
- Emit a
message
event when the user sends a new message from the client-side:
const socket = io();
const messageInput = document.getElementById('message-input');
messageInput.addEventListener('keypress', (event) => {
if (event.key === 'Enter') {
const message = event.target.value;
socket.emit('message', message);
event.target.value = '';
}
});
Testing the chat application
- Start the server:
$ node server.js
-
Open your browser and navigate to
http://localhost:3000
. You should see a chat interface. -
Open multiple browser tabs and start sending messages. The messages should be displayed in real-time on all connected tabs.
Conclusion
In this tutorial, we have built a real-time chat application using Express.js and Socket.IO. Socket.IO allows us to create real-time, bidirectional communication between the browser and the server, making it perfect for building chat applications. Express.js provides a robust and efficient framework for building the server-side of the application.
#ExpressJS #SocketIO