I use socket.io between my angular app and my server without any trouble but I don't know how to do it when it comes to use socket.io in my routes.
Here is what i did so far :
var server = app.listen(port);
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (socket) {
socket.on('server',function(data){
log.info(data.message);
});
socket.on('console',function(data){
log.info(data.message);
});
socket.emit('client',{action:"test"});
});
as i said , it works.
Now i want to use socket.io in one of my routes , routes loaded from my router :
require('./app/my.routes')(app,io);//i've tried to use it this way
module.exports = function (app,io){
io = app.get('io');//and get it this way
io.sockets.emit('socket.io :: sucessfully passed from app to router')
log.info('Trying to load express routes...');
router.use(function (req, res, next) {
next(); // make sure we go to the next routes and don't stop here
});
require('./models.mongoose/user');
//require routes
var consoleRoute = require('./express.routes/console.route')
...
and now I have that error
io.sockets.emit('socket.io :: sucessfully passed from app to router')
^
TypeError: Cannot read property 'sockets' of undefined
I must do something wrong obviously but I have no idea what. Any ideas ?
I also tried app.set('io',io) in app.js and app.get('io') on the other side but it failed all the same
Finally , i've found the solution,
app.io = io.sockets.on('connection', function (socket) {
socket.on('server', function (data) {
log.info(data);
});
socket.emit('client', {
action: "alert",
text: 'test from socket io'
});
});;
Now it's linked to app, and I can use it anywhere.
You can setup your socket io implementation in your express configuration file and pass your "io" object as a variable within the app.
app.io = io;
the idea is to do something like this:
module.exports = function (app){
app.io.sockets.emit('socket.io sucessfully passed from app to router');
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.