在路由中使用socket.io [英] Using socket.io in routes
问题描述
我在我的角度应用程序和服务器之间使用了socket.io,没有任何麻烦,但是当我在路由中使用socket.io时,我不知道该怎么做.
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.
现在我想在我的一条路由中使用socket.io,这是从路由器加载的路由:
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
my.routes.js
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')
...
现在我遇到了这个错误
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 ?
我也尝试过 app.set('io',io) 在app.js和 app.get('io') 在另一边,但都失败了
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.
推荐答案
您可以在快速配置文件中设置套接字io实现,并将"io"对象作为变量传递到应用程序中.
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;
想法是做这样的事情:
module.exports = function (app){
app.io.sockets.emit('socket.io sucessfully passed from app to router');
}
这篇关于在路由中使用socket.io的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!