I am trying to write a multi-channel application in socket.io. The channel you are in must be determined by the URL you are in. If I attach the part in app.js with constant values, everything works. As soon as I change it so that the route for route.page makes a connection, I get an error that sockets are not available in context. What would be the right way so that I can dynamically join a channel?
/app.js
var io = socketio.listen(app); require('./io')(io); io.sockets.on('connection', function (socket) { socket.on('debug', function (message) { socket.get('channel', function (err, name) { socket.in(name).broadcast.emit('debug', message); }); }); });
/io.js
var socketio = function (io) { if (!io) return socketio._io; socketio._io = io; } module.exports = socketio;
/routes/index.js
var io = require('../io')(); exports.page = function(req, res){ var channel = req.params.id; res.render('page', { title: 'PAGE', channel: channel }); io.sockets.on('connection', function (socket) { socket.join(channel); socket.set('channel', channel ); }); };
source share