Socket.io 从 Express 控制器发出 [英] Socket.io emit from Express controllers
问题描述
我对 Node.js/Express 很陌生,我将它用作 AngularJS 应用程序的后端.我在 StackOverflow 上到处寻找有关我的问题的帮助,但我似乎无法弄清楚如何将这些建议移植到我的代码中.
I'm quite new to Node.js / Express, and I'm using it as a backend for an AngularJS app. I've looked all over StackOverflow for some help on my problem, but I can't seem to figure out how to port the suggestions to my code.
我的应用程序如下:
- 长时间运行的 Scala 进程会定期发送我的 Node.js 应用程序日志消息.它通过发布到 HTTP API 来做到这一点
- 收到帖子后,我的应用程序将日志消息写入 MongoDB
- 然后将日志消息实时发送到 Angular 客户端.
我遇到了 Node 模块的问题,因为我不知道如何引用 Express 控制器中的套接字实例.
I am having a problem with Node's modules, as I can't figure out how to refer to the socket instance in the Express controller.
如你所见,在 server.js 中,socket.io 在那里被实例化.但是,我希望控制器本身,logs.js,能够使用 socket.io 实例发出.
As you can see, in server.js, socket.io is instantiated there. However, I would like the controller itself, logs.js, to be able to emit using the socket.io instance.
如何在控制器中引用io?我不确定如何将 io 实例传递给控制器以便我可以发出消息?
这里是一些节点代码:
server.js
var app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
require('./lib/config/express')(app);
require('./lib/routes')(app);
server.listen(config.port, config.ip, function() {
console.log('Express server listening on %s:%d, in %s mode', config.ip, config.port, app.get('env'));
});
io.set('log level', 1); // reduce logging
io.sockets.on('connection', function(socket) {
console.log('socket connected');
socket.emit('message', {
message: 'You are connected to the backend through the socket!'
});
});
exports = module.exports = app;
routes.js
var logs = require('./controllers/logs'),
middleware = require('./middleware');
module.exports = function(app) {
app.route('/logs')
.post(logs.create);
}
logs.js
exports.create = function(req, res) {
// write body of api request to mongodb (this is fine)
// emit log message to angular with socket.io (how do i refer to the io instance in server.js)
};
推荐答案
您可以使用基于标准 JS 闭包的模式.logs.js
中的主要导出不是控制器函数本身,而是一个工厂函数,它将接受所有需要的依赖项,并创建控制器:
You can use a pattern based on standard JS closures. The main export in logs.js
will not be the controller function itself, but a factory function that will accept all needed dependencies, and create the controller:
exports.create = function(socket) {
return function(req, res) {
// write body of api request to mongodb
socket.emit();
}
}
然后,当你想使用它时:
Then, when you want to use it:
app.route('/logs').post(logs.create(socket));
由于您在单独的包中设置了路由,因此您必须在 routes.js
中使用相同的模式 - routes
应接收套接字以用作参数.
Since you set up your routes in a separate package, you have to use the same pattern in routes.js
- routes
should receive the socket to use as a parameter.
如果您想稍后使用 DI 处理这些事情,或者使用模拟套接字"测试您的控制器,则此模式非常有效.
This pattern works well if you want to handle those things with DI later, or test your controllers with mock "sockets".
这篇关于Socket.io 从 Express 控制器发出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!