I know this might flag as a duplicate solution but solution on stack overflow is not working for me.
Problem:
(node:5716) MaxListenersExceededWarning
Default limit for Event Emitter is 10. You can increase it with emitter.setMaxListeners. My suggestion is not to change it unless and until explicitly required, listeners are increased because you didn't unsubscribed. Now to your code.
const redis = require('redis');
const config = require('../config')
const sub = redis.createClient(config.REDIS.port, config.REDIS.host);
const pub = redis.createClient(config.REDIS.port, config.REDIS.host);
sub.subscribe('spread');
module.exports = io => {
io.on('connection',(socket) => {
//COMMENT : This callback will be executed for all the socket connections.
let passport = socket.handshake.session.passport; /* To find the User Login */
if(typeof passport !== "undefined") {
socket.on('typing:send',(data) => {
pub.publish('spread',JSON.stringify(data))
});
// COMMENT : This is where you are subscribing for each and every socket conected to your server
sub.on('message',(ch,msg) => { // this is the Exact line where I am getting this error
//COMMENT : Where as you are emiting message on socket manager not on socket.
io.emit(`${JSON.parse(msg).commonID}:receive`,{...JSON.parse(msg)})
})
}
});
};
Now if we analyse above code then if you open 20 socket connection to your server it will subscribe for 20 time, here it is going wrong. Now if your requirement is to listen for the message published on redis at server level and then emit on io then your code should be like below
const redis = require('redis');
const config = require('../config')
const sub = redis.createClient(config.REDIS.port, config.REDIS.host);
const pub = redis.createClient(config.REDIS.port, config.REDIS.host);
sub.subscribe('spread');
module.exports = io => {
sub.on('message',(ch,msg) => { // this is the Exact line where I am getting this error
io.emit(`${JSON.parse(msg).commonID}:receive`,{...JSON.parse(msg)});
});
io.on('connection',(socket) => {
let passport = socket.handshake.session.passport; /* To find the User Login */
if(typeof passport !== "undefined") {
socket.on('typing:send',(data) => {
pub.publish('spread',JSON.stringify(data))
});
}
});
};