2

我正在订阅外部套接字以从套接字 api 获取数据,然后我将发布到 redis,如下所示。我得到maximum event emitter listeners exceeded errorredis.on。我无法将redis移到套接字之外,那样我将无法向套接字发送订阅数据所需的数据。如何解决这个问题?.我可以删除 on 事件中的 redis listneer 吗?

 const socketConnect=()=>{

    // Singleton Method To Avoid Multiple Socket Connections
var SingletonSocket = (function () {
    var instance;

    function createInstance() {
        var object = new WebSocket('url');
        return object;
    }

    return {
        getInstance: function () {
            if (! instance) {
                instance = createInstance();
            }
            return instance;
        }
    };
})();


/**
 * Can Subscribe rto multiple channels
 */


// here the redis subscriber givee us message that a new centralid has been added
const ws = SingletonSocket.getInstance();
const key = 'centralidslist';
const unsubscribechannel="matchunsubscribe";
const channel = "eventchannel"
ws.on('open', async function open() {
 
 log.debug({
        level: 'info',
         message:"Socket Opened Odd",
        timstamp:momenttz().tz("Asia/Kolkata").format("YYYY-MM-DD HH:mm:ss")
      });

  
redis.subscribe(channel, unsubscribechannel,async (error, count) => {
    if (error) {
        throw new Error(error);
    }
    log.debug(`Subscribed to ${channel} channel. Listening for updates on the ${channel} channel.`);
    await data.publish(channel,"Publishing First Time"); // publishing the event to the channel so that socket subscription can be started
});

    

    redis.on('message', async (channel, message) => {

     /// How to remove listener once the message is recieved and done processing


        if(channel==unsubscribechannel)


        {
            ws.send();
            redis.removeListners();  // is it a good practice to do it here ?
        }


        else{
           ws.send();
           
        }


    });

    

    
});

ws.on('error', function(error) {
    log.debug({
        level: 'info',
        message:"Socket Error Unable To Connect To URl"+error,
        timstamp:momenttz().tz("Asia/Kolkata").format("YYYY-MM-DD HH:mm:ss")
      });
});

ws.on('close', function close() {
    log.debug({
        level: 'info',
        message:"Socket Closed",
        timstamp:momenttz().tz("Asia/Kolkata").format("YYYY-MM-DD HH:mm:ss")
      });
    setTimeout(()=>{
        console.log("Trying to Reconnect");
        log.debug({
            level: 'info',
            message:"Trying To Reconnect To Socket",
            timstamp:momenttz().tz("Asia/Kolkata").format("YYYY-MM-DD HH:mm:ss")
          });
        socketConnect()}, 5000)
  });
   


ws.on('message', async function incoming(message) {

  

});




}


    socketConnect();
4

0 回答 0