我需要从服务器代码路由器/控制器上的任何位置从服务器发出套接字。我检查了一些线程和谷歌但没有按预期工作。
app.js
var app = require('express').createServer();
var io = require('socket.io')(app);
require(./router.js)(app)
require(./socket.js)(io)
app.listen(80);
router.js
module.exports = function (app) {
app.use('/test', require(./controller.js));
return app;
};
socket.js
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
controller.js
var express = require('express');
var router = express.Router();
router.get('/about', function(req, res) {
// I need to emit here
});
module.exports = router;
这不是我正在使用的提取代码。这是我使用的结构以及我需要调用的地方。
答案 0 :(得分:6)
您将需要io
个对象来发出事件。
流程1: 将io作为全球(快速修复)传递
<强> app.js 强>
var app = require('express').createServer();
var io = require('socket.io')(app);
global.io = io; //added
require(./socket.js)(io)
app.listen(80)
<强> controller.js 强>
router.get('/about', function(req, res) {
// I need to emit here
global.io.emit('news', { hello: 'world' });
});
备注:强> 至于传递io对象。你有几个选择,可能是也可能不是最佳选择。
可能最简单的方法是传递作为控制器的参数,同时在路由中要求它们。
流程2: 将io作为参数传递
<强> app.js 强>
var app = require('express').createServer();
var io = require('socket.io')(app);
require(./router.js)(app,io);
require(./socket.js)(io);
app.listen(80);
<强> router.js 强>
/*
* Contains the routing logic
*/
module.exports = function (app,io) {
//passing while creating the instance of controller for the first time.
var controller = require("./controller")(io);
app.get('/test/about',controller.myAction);
};
<强> controller.js 强>
module.exports = function(io){
var that={};
/*
* Private local variable
* made const so that
* one does not alter it by mistake
* later on.
*/
const _io = io;
that.myAction = function(req,res){
_io.emit('news', { hello: 'world' });
res.send('Done');
}
// everything attached to that will be exposed
// more like making public member functions and properties.
return that;
}