gpt4 book ai didi

javascript - Socket.io 从 HTTP API Controller 触发事件

转载 作者:行者123 更新时间:2023-12-03 04:07:43 25 4
gpt4 key购买 nike

在我的 Node+Express 服务器应用程序中,我想从来自 HTTP API 的请求触发的特定 Controller 发出通知:

例如:

router.route('/status').put(Order.changeStatus)

class Order {
static changeStatus(req, res) {
// Modifying database record with changed status
// Emiting message to specific socket room
}
}

我按如下方式处理套接字连接:

import AuthMiddleware from '../middleware/AuthMiddleware';

const socketio = require('socket.io');
let io;

module.exports.listen = function(app){
io = socketio.listen(app);

io.on('connection', function(socket){
console.log('Client connected');

AuthMiddleware.authenticateSocket(socket, (err, user) => {
socket.join(user._id);
console.log('Client joined to: ' + user._id);
})

socket.on('disconnect', () => {
console.log('Client disconnected')
});
});

return io;
}

验证传入的套接字连接后,订阅自己ID的房间。

套接字在项目顶部初始化如下:

import app from './app';
import http from 'http';


const PORT = process.env.PORT || 7235;
const server = http.createServer(app);

const io = require('./socket/main').listen(server);

// App start
server.listen(PORT, err => {
console.log(err || `Server listening on port ${PORT}`);
});

虽然我能够处理传入事件并响应这些事件,但此结构的问题是我无法访问 Controller 内的 io 对象以便能够在特定房间中发出数据,如下所示:

io.sockets.in(userID).emit('notification', data);

能够从 HTTP API Controller 触发套接字事件的正确结构是什么?

最佳答案

您的 Controller 需要有权访问已配置的 io 对象。最简单的方法是将其导出到模块中,而不仅仅是导出监听函数,也许像这样:

import AuthMiddleware from '../middleware/AuthMiddleware';

const socketio = require('socket.io');
let io;

function listen(app){
io = socketio.listen(app);

io.on('connection', function(socket){
console.log('Client connected');

AuthMiddleware.authenticateSocket(socket, (err, user) => {
socket.join(user._id);
console.log('Client joined to: ' + user._id);
})

socket.on('disconnect', () => {
console.log('Client disconnected')
});
});

return io;
}

module.exports = {
listen, io
}

然后你的 Controller 就可以执行 const io = require('./path/to/that').io;

关于javascript - Socket.io 从 HTTP API Controller 触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44473180/

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