从NodeJS中的模型访问套接字控制器

时间:2017-02-22 16:33:37

标签: node.js socket.io

所以我正在开展一个学校项目,我们有一个代码模板。 我有一个运行的mysql数据库,每当某个表获得插入时,我希望任何查看网站上的表的人都使用socket.io更新它。 但我无法从模型中访问socketcontroller,也无法从routecontroller(我称之为模型)访问socketcontroller。我理解将插入的数据返回控制器(通过回调)然后在控制器中使用io发出消息可能是最好的做法。

index.js中的

var httpServer = http.Server(app);
var io = require('socket.io').listen(httpServer);
io.use(sharedsession(session));

var router = require('./controller.js');
app.use('/API', router);

var socketController = require('./socketController.js');
io.on('connection', function (socket) {
    socketController(socket, io);
});
var model = require('./model.js');
socketController.js中的

module.exports = function (socket, io) {
    socket.on('join', function (req) {
        console.log(req);
        var security = req.security;
        socket.join(security);
    });

    socket.on('update', function (req) {
        //this is the function i want to "call" from the model/routecontroller
    });
}

在controller.js

router.post('/orders', function(req, res) {
    //var socket = io(); <--- not defined
    model.matchOrder(req.body, function(result) {
        res.json({order: req.body});
    })
});

在model.js中

function createTrade(security, price, amount, buyer, seller) {
    console.log("Trade created");
    //var socket = io()    <-- not defined 
    Trades.create({
      security: security,
      price: price,
      amount: amount,
      buyer: buyer,
      seller: seller
    });

}

所以1.我应该在controller.js或model.js中尝试访问套接字? 2.如何从controller.js / model.js访问io()?

0 个答案:

没有答案
相关问题