socket io path code example
Example 1: socket io connect to namespace
var io = require('socket.io')(http, { path: '/myapp/socket.io'});
io
.of('/my-namespace')
.on('connection', function(socket){
console.log('a user connected with id %s', socket.id);
socket.on('my-message', function (data) {
io.of('my-namespace').emit('my-message', data);
console.log('broadcasting my-message', data);
});
});
Example 2: 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);
});
});