事件发射器的默认限制为10。您可以使用generator.setMaxListeners增加它。我的建议是不要更改它,除非并且直到明确要求为止,因为您没有取消订阅,所以增加了侦听器。现在到您的代码。
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)})
})
}
});
};
现在,如果我们分析以上代码,则如果您打开与服务器的20个套接字连接,它将订阅20次,这是错误的。现在,如果您的要求是在服务器级别上侦听在redis上发布的消息,然后在io上发出,则您的代码应如下所示
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))
});
}
});
};