Socket.IO Documentation || Devstream365
Socket.IO Documentation
Socket.IO is a library for real-time, bidirectional, and event-based communication between web clients and servers. It is built on top of WebSockets and includes fallbacks for older browsers.
Installation
Install Socket.IO in both your server and client projects using npm or yarn.
Server-side Installation:
npm install socket.io
Client-side Installation:
npm install socket.io-client
Alternatively, use a CDN for the client:
<script src="https://cdn.socket.io/4.6.0/socket.io.min.js"></script>
Basic Usage
Server-side Example
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
io.on('connection', (socket) => {
console.log('A user connected');
// Handle custom events
socket.on('message', (data) => {
console.log('Message received:', data);
});
// Disconnect event
socket.on('disconnect', () => {
console.log('A user disconnected');
});
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
Client-side Example
import { io } from 'socket.io-client';
const socket = io('http://localhost:3000');
// Listen for connection event
socket.on('connect', () => {
console.log('Connected to server');
});
// Emit a message event
socket.emit('message', 'Hello, server!');
// Listen for disconnect
socket.on('disconnect', () => {
console.log('Disconnected from server');
});
Features
1. Namespaces
Namespaces allow you to create multiple, independent communication channels.
Server-side:
const chatNamespace = io.of('/chat');
chatNamespace.on('connection', (socket) => {
console.log('User connected to chat namespace');
});
Client-side:
const chatSocket = io('http://localhost:3000/chat');
2. Rooms
Rooms allow grouping sockets to broadcast messages to a subset of connected clients.
Joining a Room:
socket.join('room1');
socket.to('room1').emit('message', 'Hello, Room 1!');
Leaving a Room:
socket.leave('room1');
3. Broadcasting
Broadcast messages to all connected sockets except the sender.
socket.broadcast.emit('message', 'This is a broadcast message');
4. Middleware
Use middleware to intercept and process events.
Example Middleware:
io.use((socket, next) => {
const token = socket.handshake.auth.token;
if (isValidToken(token)) {
next();
} else {
next(new Error('Authentication error'));
}
});
Advanced Topics
Error Handling
Use the error
event to handle errors:
socket.on('connect_error', (err) => {
console.error('Connection error:', err.message);
});
Sending and Receiving Binary Data
Socket.IO supports binary data, such as files or images:
Sending:
socket.emit('file', fileBuffer);
Receiving:
socket.on('file', (data) => {
console.log('Received file:', data);
});
Integration with Express
Combine Socket.IO with an Express app:
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket) => {
console.log('User connected');
});
Debugging
Enable debugging logs using the DEBUG
environment variable:
DEBUG=socket.io:* node app.js
Best Practices
- Authentication: Use middleware to authenticate users.
- Scalability: Use adapters like Redis for scaling across multiple servers.
- Error Handling: Always handle errors gracefully.
- Data Validation: Validate data sent by clients to prevent malicious input.
Resources
Conclusion
Socket.IO is a powerful tool for building real-time applications such as chat apps, gaming platforms, and live data dashboards. Its simplicity and flexibility make it an essential library for modern web development.