node.js - How to make eventEmitter and socket io friends
问题描述
I ran into the problem of infinitely creating event listeners: There is a socketIo connection handler: It sets the eventEmitter event handler, when the event is bubbling, the handler is triggered on everyone connected to the socket
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', () => {
})
}
and emit
emitter.emit('redirectGamePage', {
users: {
black: game.playerBlack,
white: game.playerWhite
},
gameId
});
I tried to constrain using setMaxListeners function, but all i get is a warning: MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 2 redirectGamePage listeners added to [EventEmitter]. Use emitter. setMaxListeners () to increase limit
解决方案
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'
});
});
}
推荐阅读
- python - 为什么我在从不同进程读取文件时出现竞争条件?
- c++ - 了解 C++ - “字符文字”与“字符串文字”
- tensorflow-serving - Tensorflow 服务 - 正确的 JSON 签名
- javascript - Vue.js - 从 axios 返回数组
- python - 在字典中查找与特定 int/float 最接近的 int/float 键
- ionic-framework - fcm cordova 插件在 ios 设备上不起作用
- c# - Unity,为精灵添加像素和颜色
- node.js - 如何将数组解构为 POSTGRES 参数?
- python - 更改列表python中多个项目的值
- ios - 从 Firebase 数据库中检索整数,结果一无所有