Express.js and Socket.io
Socket.io is a library that enables real-time, bidirectional, and event-based communication between web clients and servers. This guide covers key concepts, examples, and best practices for using Socket.io in Express.js applications.
Key Concepts of Socket.io
- Real-Time Communication: Enables instant communication between clients and servers.
- Event-Based: Communication is based on custom events emitted and listened to by clients and servers.
- Bidirectional: Supports two-way communication between clients and servers.
Setting Up Socket.io
Integrate Socket.io with an Express.js server:
Example: Basic Setup
// server.js
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);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
// index.html
Socket.io Example
Socket.io Example