gpt4 book ai didi

node.js - Socket.IO + Express 框架 |从 Express Controller 和路由器发射/发射

转载 作者:搜寻专家 更新时间:2023-10-31 22:39:10 26 4
gpt4 key购买 nike

我需要从服务器代码、路由器/ Controller 上的任何位置发出来自服务器的套接字。我检查了一些线程和谷歌,但没有按预期工作。

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

套接字.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;

这不是我使用的提取代码。这是我正在使用的结构以及我需要调用的地方。

最佳答案

您将需要 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 对象。您有几个选择,可能是也可能不是最好的。

  • 使 io 全局化。 (改变全局需求护理)
  • 使用 module.exports 并要求其他文件中的对象。 (如果处理不当会导致循环依赖问题)

Probably, the cleanest way is to pass is as arguments to the controllers, while requiring them in routes.

流程 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;
}

关于node.js - Socket.IO + Express 框架 |从 Express Controller 和路由器发射/发射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36904048/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com