ExpressJS + Socket.IO路由

时间:2016-01-10 18:59:20

标签: node.js routes socket.io emit

重复的问题,但我发现没有完美的答案作为解决方案。请帮我解决这个问题。

我的App.js

   var routes = require('./routes/index');
   var users = require('./routes/users');
   var media = require('./routes/media');
   var widget = require('./routes/widget');
   var display = require('./routes/displays');
   var device = require('./routes/deviceinfo');

   app.use('/', routes);
   app.use('/display', display);


   var server = http.createServer(app);
   var io = require('socket.io')(server);
   io.set('transports', ['polling', 'websocket']);

显示路线:" routes / display.js"

我有插入显示的代码,一旦创建了显示,事件应该发送到设备列表。

Emit应该写成保存成功回调方法。

      var express = require('express');
      var router = express.Router(); 
      router.post('/save', action_save_displays);
      function action_save_displays(req, res){
        display.save(req,body , function(err , display){
               if(!err){
                res.json(display);
                 //io.sockets.emit("displaycreated", display);
              }
        })
      }
       module.exports = routes;

如何在routes / display.js文件中传递io.sockets.emit。真的很感谢你的指导。如何将socket对象发送到路由以启用emit事件。

1 个答案:

答案 0 :(得分:1)

你可以稍微交换一下需求,然后将socket.io传递给display.js文件

var routes  = require('./routes/index');
var users   = require('./routes/users');
var media   = require('./routes/media');
var widget  = require('./routes/widget');

var server  = http.createServer(app);
var io      = require('socket.io')(server);
var display = require('./routes/displays')(io); // here

var device  = require('./routes/deviceinfo');

app.use('/', routes);
app.use('/display', display);

io.set('transports', ['polling', 'websocket']);

并在display.js文件

中获取
 var express = require('express');
 var router = express.Router(); 

 module.exports = function(io) {

     router.post('/save', function(req, res) {
         display.save(req.body , function(err, display){
             if(!err){
                 res.json(display);
                 io.sockets.emit("displaycreated", display);
              }
         });
     });

    return router;
}