Express.js and WebSockets
WebSockets provide full-duplex communication channels over a single TCP connection, enabling real-time communication between the client and server. This guide covers key concepts, examples, and best practices for implementing WebSockets in Express.js applications.
Key Concepts of WebSockets
- Full-Duplex Communication: Allows simultaneous two-way communication between the client and server.
- WebSocket Protocol: A protocol providing full-duplex communication channels over a single TCP connection.
- Socket.IO: A library that enables real-time, bidirectional event-based communication.
Setting Up the Project
Initialize a new Express.js project and install necessary dependencies:
// Initialize a new project
// npm init -y
// Install Express and Socket.IO
// npm install express socket.io
// Create the project structure
// mkdir src
// touch src/index.js public/index.html .gitignore
// .gitignore
node_modules
.env
Setting Up the Express and Socket.IO Server
Configure the Express application to use Socket.IO for real-time communication:
Example: index.js
// src/index.js
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 3000;
const server = http.createServer(app);
const io = socketIo(server);
app.use(express.static('public'));
io.on('connection', (socket) => {
console.log('New client connected');
socket.on('message', (data) => {
console.log('Message received:', data);
io.emit('message', data);
});
socket.on('disconnect', () => {
console.log('Client disconnected');
});
});
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
Creating the Client-Side Code
Create the HTML and JavaScript for the client to connect to the WebSocket server and send/receive messages:
Example: index.html
// public/index.html
WebSocket Chat
WebSocket Chat