首页 > 解决方案 > 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

标签: node.jssocket.io

解决方案


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'
        });
      });
    }

推荐阅读