Step-by-Step WebSocket Tutorial with Socket.io
1. Project Setup
Create Project DirectoryCreate a new directory for your project and navigate into it:
mkdir socketio-tutorial
cd socketio-tutorial
Initialize Node.js Project
Initialize a new Node.js project:
npm init -yInstall Dependencies
Install express for the server and socket.io for WebSocket functionality:
npm install express socket.ioProject Structure
Your project directory should look like this:
socketio-tutorial/
├── node_modules/
├── public/
│ ├── index.html
├── src/
│ ├── index.js
├── package.json
└── package-lock.jsonCreate the Server
- Create
src/index.jsThis is where your server code will reside. Create theindex.jsfile in thesrcdirectory:
// src/index.js
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
// Initialize express application
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
// Serve static files from the 'public' directory
app.use(express.static('public'));
// Handle WebSocket connections
io.on('connection', (socket) => {
console.log('A new client connected');
// Listen for chat messages from the client
socket.on('chat message', (msg) => {
console.log('Message received:', msg);
// Broadcast the message to all clients
io.emit('chat message', msg);
});
// Handle client disconnections
socket.on('disconnect', () => {
console.log('Client disconnected');
});
});
// Start the server on port 3000
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Part-by-Part Breakdown of index.js
1. Setup and Initialization
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
Explanation:
express: A web framework for Node.js used to create the server.http: Node.js module to handle HTTP requests. We use it to create a server instance.socketIo: The Socket.io library to enable WebSocket functionality.
Explanation:
io: The Socket.io server instance. It will be attached to the HTTP server, allowing WebSocket connections.
2. Create Express Application and HTTP Server
const app = express();
const server = http.createServer(app);Explanation:
app: The Express application instance.server: The HTTP server created using the Express app. This server will be used by Socket.io to handle WebSocket connections.
3. Initialize Socket.io
const io = socketIo(server);Explanation:
io: The Socket.io server instance. It will be attached to the HTTP server, allowing WebSocket connections.
4. Serve Static Files
app.use(express.static('public'));Explanation:
express.static('public'): Middleware that serves static files (e.g., HTML, CSS, JavaScript) from thepublicdirectory. This makes files inpublicaccessible to clients.
5. Handle WebSocket Connections
io.on('connection', (socket) => {
console.log('A new client connected');Explanation:
io.on('connection', (socket) => { ... }): Event listener for new WebSocket connections. When a client connects, the provided callback function is executed, and thesocketobject represents the connected client.
6. Listen for Chat Messages
socket.on('chat message', (msg) => {
console.log('Message received:', msg);
io.emit('chat message', msg);
});Explanation:
socket.on('chat message', (msg) => { ... }): Event listener for chat messages sent by the client. When achat messageevent is received, it logs the message and broadcasts it to all connected clients usingio.emit.
7. Handle Client Disconnections
socket.on('disconnect', () => {
console.log('Client disconnected');
});
});
Explanation:
socket.on('disconnect', () => { ... }): Event listener for when a client disconnects. It logs the disconnection event.
8. Start the Server
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Explanation:
PORT: The port number on which the server will listen.server.listen(PORT, () => { ... }): Starts the server on the specified port and logs a message indicating that the server is running.