使 socket.io 成为单例的最佳方法是什么?这里我有三个文件,我需要在user.mjs
中使用socket.io方法socket.mjs
class socketBusiness extends baseBusiness {
//io = null;
//connectedUsers = {}
constructor(io) {
super(io);
this.io = io;
this.connectedUsers = {};
this.addUserRef= {};
this.bindEvents();
}
bindEvents() {
this.io.on("connection", this.onConnection);
this.io.use(this.onBeginConnection);
}
unBindEvents() {
this.io.off("connection", this.onConnection);
}
onConnection(socket) {
let _io = this.io;
let socketId = socket.id;
socket.on("disconnect", reason => {
});
socket.on("chat message", function(msg) {
});
}
addUserRef(userId, cstId) {
let arr = this.addUserRef[cstId] || [];
if (arr.indexOf(cstId) < 0) {
arr.push(cstId);
}
this.addUserRef[userId] = arr;
}
}
export default socketBusiness;
用户.mjs
const socket = require("socket.mjs)
export async function addCst(req, res) {
socket.addUserRef(req.id,req.cstId)
}
我如何访问socket.io方法?任何帮助将不胜感激
www.mjs
import socket from '../socket.mjs';
var server = createServer(app);
var io = new SocketServer(server, {})
var sb = new socketBusiness(io);
最佳答案
导出实例:
export default new socketBusiness;
如果导出单例,则无法在构造函数中传递 io。将初始化逻辑移至方法中:
constructor() { }
init(io) {
this.io = io;
this.bindEvents();
}
然后,在获得套接字时初始化单例:
var io = new SocketServer(server, {})
socket.init(io);
关于javascript - 需要将socket.io类更改为singleton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58371508/