Handling Events with Socket.IO
Socket.IO enables real-time communication by allowing event-based interactions between the client and server. Here's how to handle various events effectively.
1. Event Types in Socket.IO
message
, notification
).2. Server-Side Event Handling
Basic Server Setup
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');
// Listening for custom events
socket.on('chat message', (msg) => {
console.log('Message received:', msg);
io.emit('chat message', msg); // Broadcast the message
});
// Handling disconnection
socket.on('disconnect', () => {
console.log('User disconnected');
});
});
server.listen(3000, () => console.log('Server running on port 3000'));
3. Client-Side Event Handling
Basic Client Setup
4. Broadcasting and Rooms
Socket.IO makes it easy to broadcast messages or create chat rooms.
Broadcasting to All Clients
socket.on('chat message', (msg) => {
io.emit('chat message', msg); // Send to all connected clients
});
Using Rooms
socket.on('join room', (room) => {
socket.join(room); // Join a specific room
io.to(room).emit('message', `User joined room: ${room}`);
});
5. Error Handling
Socket.IO includes built-in error events.
socket.on('error', (err) => {
console.error('Socket.IO error:', err);
});