需要将socket.io类更改为单例
使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();
}
unBindEvents() {
this.io.off("connection", this.onConnection);
}
onConnection(socket) {
let _io = this.io;
let socketId = socket.id;
let transport = socket.conn.transport.name;
let address = socket.handshake.address;
logHelper.logInfo(
`a user connected with transport: ${transport}, ip: ${address}`
);
//socket.broadcast.emit('hi');
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;
需要将socket.io类更改为单例
使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();
}
unBindEvents() {
this.io.off("connection", this.onConnection);
}
onConnection(socket) {
let _io = this.io;
let socketId = socket.id;
let transport = socket.conn.transport.name;
let address = socket.handshake.address;
logHelper.logInfo(
`a user connected with transport: ${transport}, ip: ${address}`
);
//socket.broadcast.emit('hi');
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;