需要将socket.ioclass改为单例

Need to change socket.io class to singleton

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

user.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();
}

然后,在拿到socket后初始化单例:

var io = new SocketServer(server, {})
socket.init(io);