سؤال

I am trying to write a multi channel application in socket.io. The channel you are in should be defined by the url you are on. If I do the joining part in the app.js with permanent values everything works. As soon as I change it so that the route for route.page does the joining I get the error, that sockets is not available in the context. What would be the correct way so that I can dynamically join the 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 );
  });
};
هل كانت مفيدة؟

المحلول

The easiest way I've found to do multiple channels is off of different URLs.

For example I have the client do the following:

io.connect('/game/1')
io.connect('/system')

and on the server I have

io.of('/game/1').on('connect' function(socket) {...})
io.of('/system').on('connect' function(socket) {...})

It looks like I'm connecting twice here, but socket.io is smart enough to use a single websocket for this connection (at least it says so in the how-to-use).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top