Working with routes in js and socket.io expressions and possibly node in general

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 ); }); }; 
+4
source share
1 answer

The easiest way to find multiple channels is with different URLs.

For example, I have a client:

 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 web site for this connection (at least this tells how to use it).

+3
source

Source: https://habr.com/ru/post/1390336/


All Articles