This tutorial aims to guide you in integrating Socket.io with Express.js to create real-time, bi-directional communication for your web applications.
At the end of this tutorial, you should understand how to set up an Express.js server that uses Socket.io for real-time communication.
You should have a basic understanding of JavaScript and Node.js. Familiarity with Express.js will also be helpful.
First, we need to install Express.js and Socket.io. In your project directory, run:
npm install express socket.io
Create a new file, index.js
, in your project directory and add the following code:
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);
io.on('connection', (socket) => {
console.log('New client connected');
socket.on('disconnect', () => {
console.log('Client disconnected');
});
});
server.listen(3000, () => {
console.log('Listening on port 3000');
});
Your index.js
should look like this:
const express = require('express');
const http = require('http');
const socketio = require('socket.io');
const app = express(); // Instantiate Express.js application
const server = http.createServer(app); // Create an HTTP server with Express.js app
const io = socketio(server); // Attach Socket.io to the HTTP server
// Listen for new connections from clients
io.on('connection', (socket) => {
console.log('New client connected');
// Listen for disconnect event on this socket
socket.on('disconnect', () => {
console.log('Client disconnected');
});
});
// Start the HTTP server on port 3000
server.listen(3000, () => {
console.log('Listening on port 3000');
});
In this tutorial, we have installed Express.js and Socket.io, set up a basic Express.js server, and integrated Socket.io to enable real-time, bi-directional communication between the server and clients.
As next steps, you could explore more Socket.io features, such as rooms and namespaces, or build a chat application.
Update the server code to echo back any message it receives from a client.
Extend the server to broadcast a message received from a client to all other connected clients.
Create a chat room where clients can join and leave, and messages are only broadcasted to clients in the same room.
Note: Solutions for the exercises are not included here, but you can find them in the Socket.io and Express.js documentation or online tutorials. Good luck!