想法是当有人点击路由
/add-team-member
并将其保存到我的Mongo db时,向所有连接到WebSocket且属于与该团队对应的WebSocket房间的人员发出消息。我已经按照socket.io的文档设置了我的应用程序,如下所示: App.js
// there's a lot of code in here which sets what to use on my app but here's the important lines
const app = express();
const routes = require('./routes/index');
const sessionObj = {
secret: process.env.SECRET,
key: process.env.KEY,
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection }),
secret : 'test',
cookie:{_expires : Number(process.env.COOKIETIME)}, // time im ms
}
app.use(session(sessionObj));
app.use(passport.initialize());
app.use(passport.session());
module.exports = {app,sessionObj};
start.js
const mongoose = require('mongoose');
const passportSocketIo = require("passport.socketio");
const cookieParser = require('cookie-parser');
// import environmental variables from our variables.env file
require('dotenv').config({ path: 'variables.env' });
// Connect to our Database and handle an bad connections
mongoose.connect(process.env.DATABASE);
// import mongo db models
require('./models/user');
require('./models/team');
// Start our app!
const app = require('./app');
app.app.set('port', process.env.PORT || 7777);
const server = app.app.listen(app.app.get('port'), () => {
console.log(`Express running → PORT ${server.address().port}`);
});
const io = require('socket.io')(server);
io.set('authorization', passportSocketIo.authorize({
cookieParser: cookieParser,
key: app.sessionObj.key, // the name of the cookie where express/connect stores its session_id
secret: app.sessionObj.secret, // the session_secret to parse the cookie
store: app.sessionObj.store, // we NEED to use a sessionstore. no memorystore please
success: onAuthorizeSuccess, // *optional* callback on success - read more below
fail: onAuthorizeFail, // *optional* callback on fail/error - read more below
}));
function onAuthorizeSuccess(data, accept){}
function onAuthorizeFail(data, message, error, accept){}
io.on('connection', function(client) {
client.on('join', function(data) {
client.emit('messages',"server socket response!!");
});
client.on('getmessage', function(data) {
client.emit('messages',data);
});
});
我的问题是,我有很多在./routes/index
文件中进行的mongo DB保存操作,我希望能够从我的路由中发送消息,而不是从连接了socket.io的start.js的结尾处发出。
即使IO在start.js中设置,是否有任何方法可以从我的./routes/index
文件中发出websocket消息?
例如像这样:
router.get('/add-team-member', (req, res) => {
// some io.emit action here
});
也许我需要移动初始化socket.io的位置,但是我没有找到任何文档说明这一点,或者我可以在路由中已经以某种方式访问socket.io吗?
谢谢并感谢您的帮助,如果有不清楚的地方,请告诉我!
io
实例向所有客户端广播消息。https://dev59.com/UWs05IYBdhLWcg3wQvoe - WoodyWoodsta