我遇到了无限创建事件侦听器的问题:有一个socketIo连接处理程序:它设置eventEmitter事件处理器,当事件冒泡时,在连接到套接字的每个人上触发处理程序
async connectionMainNamespace(socket) {
const {userId} = socket.handshake.query;
socket.join(userId);
emitter.addListener('redirectGamePage', (data) => {
console.log('emmiter');
socket.to(data.users.black).emit('redirectGamePage', {
gameId: data.gameId,
color: 'black'
});
socket.to(data.users.white).emit('redirectGamePage', {
gameId: data.gameId,
color: 'white'
});
});
socket.on('disconnect', () => {
})
}
和排放
emitter.emit('redirectGamePage', {
users: {
black: game.playerBlack,
white: game.playerWhite
},
gameId
});
我试图约束使用setMaxListeners函数,但所有我得到的是一个警告:MaxListenersExceededWarning:可能的EventEmitter内存泄漏检测。[EventEmitter]中增加了2个redirectGamePage监听器。使用发射器。setMaxListeners()增加限制
if (emitter.listenerCount('redirectGamePage') < 1) {
console.log('emitter');
emitter.on('redirectGamePage', (data) => {
socket.to(data.users.black).emit('redirectGamePage', {
gameId: data.gameId,
color: 'black'
});
socket.to(data.users.white).emit('redirectGamePage', {
gameId: data.gameId,
color: 'white'
});
});
}