【问题标题】:Using socket.io in routes在路由中使用 socket.io
【发布时间】:2016-10-18 15:02:38
【问题描述】:

我在我的 Angular 应用程序和我的服务器之间使用 socket.io 没有任何问题,但是在我的路由中使用 socket.io 时我不知道该怎么做。

这是我到目前为止所做的:

app.js

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"});
});

正如我所说,它有效。

现在我想在我的一条路由中使用 socket.io,路由从我的路由器加载:

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

我肯定做错了什么,但我不知道是什么。 有什么想法吗?

我也试过 app.set('io',io) 在 app.js 和 app.get('io') 在另一边,但它同样失败了

解决方案

终于找到解决办法了,

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'
  });
});;

现在它已链接到应用程序,我可以在任何地方使用它。

【问题讨论】:

    标签: javascript angularjs node.js sockets


    【解决方案1】:

    您可以在您的快速配置文件中设置您的套接字 io 实现,并将您的“io”对象作为变量传递给应用程序。

    app.io = io;
    

    我们的想法是做这样的事情:

    module.exports = function (app){ 
        app.io.sockets.emit('socket.io sucessfully passed from app to router');
    }
    

    【讨论】:

    • 你的意思是:app.io = io 在我的 app.js 中,然后 var x = require(somefile)(app,io) 所以我可以在像 io.emit(.. ..) ?
    • 只需传递应用程序,因为它已经引用了 io 对象,如 require("routes")(app)
    • 好的,现在没有错误了,但它完全安静,就像什么都没发生一样。奇怪。我会继续调查。
    • 测试你是否让它工作(在服务器中)可能你在客户端有另一个问题看看这个答案stackoverflow.com/questions/30719155/…
    • 谢谢你,我找到了解决方案。帖子已编辑
    猜你喜欢
    • 1970-01-01
    • 2013-09-22
    • 2018-06-17
    • 1970-01-01
    • 2019-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-10
    相关资源
    最近更新 更多