socket io authentication middleware code example
Example: socket io middleware
const express = require('express');
const socketio = require('socket.io');
const port = 3000;
const app = express();
const server = app.listen(port, console.log(`Listening on port ${port}...`));
const io = socketio(server);
io.use((socket, next) => {
if () {
next();
} else {
next(new Error('Connection failed.'));
}
});
io.on('connection', (socket) => {
socket.use((packet, next) => {
const event = packet[0];
const data = packet.slice(1);
if () {
next();
} else {
next(new Error('Failed to emit the event.'));
}
});
socket.on('msg', (data) => {
socket.broadcast.emit('msg', data.msg);
});
});