6.1. Rooms and Namespaces
Rooms and namespaces allow for more organized communication:
- Rooms: Useful for broadcasting messages to specific groups of clients. For example, you might use rooms to create chat channels or multiplayer game lobbies.Server-side Example:
io.on('connection', (socket) => { console.log('A user connected'); // Join a room socket.on('join room', (room) => { socket.join(room); console.log(`User joined room: ${room}`); }); // Leave a room socket.on('leave room', (room) => { socket.leave(room); console.log(`User left room: ${room}`); }); // Broadcast message to a specific room socket.on('message to room', (room, msg) => { io.to(room).emit('room message', msg); }); });
- Client-side Example:
const socket = io(); // Join room socket.emit('join room', 'room1'); // Send message to room socket.emit('message to room', 'room1', 'Hello Room 1!'); // Listen for messages from the room socket.on('room message', (msg) => { console.log('Message from room:', msg); });
- Namespaces: They create separate communication channels with their own set of events and rooms. For example, you might have a
chat
namespace and anotifications
namespace.Server-side Example:
javascriptCopy codeconst chatNamespace = io.of('/chat'); const notificationsNamespace = io.of('/notifications'); chatNamespace.on('connection', (socket) => { console.log('A user connected to chat namespace'); socket.on('chat message', (msg) => { chatNamespace.emit('chat message', msg); }); }); notificationsNamespace.on('connection', (socket) => { console.log('A user connected to notifications namespace'); socket.on('notification', (notification) => { notificationsNamespace.emit('notification', notification); }); });
- Client-side Example:
<script src="/socket.io/socket.io.js"></script> <script> const chatSocket = io('/chat'); const notificationsSocket = io('/notifications'); chatSocket.on('chat message', (msg) => { console.log('Chat message:', msg); }); notificationsSocket.on('notification', (notification) => { console.log('Notification:', notification); }); chatSocket.emit('chat message', 'Hello Chat!'); notificationsSocket.emit('notification', 'New notification!'); </script>
6.2. Middleware
Socket.io allows you to use middleware for handling authentication and other pre-processing tasks before a client connects or emits an event.
Server-side Example:
const io = require('socket.io')(server);
// Middleware to authenticate clients
io.use((socket, next) => {
const token = socket.handshake.query.token;
if (isValidToken(token)) {
next();
} else {
next(new Error('Authentication error'));
}
});
io.on('connection', (socket) => {
console.log('A user connected');
});
Client-side Example:
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io({
query: {
token: 'your-authentication-token'
}
});
socket.on('connect', () => {
console.log('Connected to server');
});
socket.on('connect_error', (error) => {
console.error('Connection error:', error);
});
</script>
6.3. Broadcasting
You can use broadcasting to send messages to all clients except the sender or to a subset of clients.
- Broadcast to All Clients Except the Sender:Server-side Example:
socket.broadcast.emit('message', 'Hello everyone except this user');
- Broadcast to All Clients in a Room:Server-side Example:
io.to('room1').emit('room message', 'Hello room 1!');
6.4. Handling Disconnections
Handling disconnections gracefully is important for maintaining a good user experience.
Server-side Example:
io.on('connection', (socket) => {
console.log('A user connected');
socket.on('disconnect', () => {
console.log('User disconnected');
});
});
Client-side Example:
socket.on('disconnect', () => { console.log('Disconnected from server');
});
Leave a Reply