【问题标题】:How to fix MaxListeners warning in node.js+socket.io? What is wrong with my code?如何修复 node.js+socket.io 中的 MaxListeners 警告?我的代码有什么问题?
【发布时间】:2021-05-22 13:41:03
【问题描述】:

0|服务器 | (节点:22094) MaxListenersExceededWarning:检测到可能的 EventEmitter 内存泄漏。 11 个唤醒监听器添加到 [Connection]。使用emitter.setMaxListeners() 增加限制

我得到的确切错误。^

这是我的 io 代码:

io.on('connection', (client) => {
console.log('Client connected: ', client.id);
let userId;

if (client.handshake.headers.authorization) {
    jwt.verify(client.handshake.headers.authorization, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
        if (err) return err;
        userId = decoded.username;
        functions.changeOnlineStatus(decoded.username, true);
        let userDTO = { id: userId, onlineStatus: true };
        io.emit('/topic/online-status', userDTO);
    });
}

client.on('/app/conversation/chat', (data) => {
    if (data.type != null) {
        switch (data.type) {
            case "edit":
                let editDto = {
                    "messageData": Buffer.from(data.messageData),
                    "messageType": data.messageDataType,
                    "messageMimeType": data.messageMimeType,
                    "conversationId": data.conversationId,
                    "id": data.serverId,
                    "sentAt": data.date,
                    "sender": { "id": data.senderId },
                    "receiver": { "id": data.receiverId },
                    "address": data.address,
                    "type": "edit"
                };
                io.emit('/topic/chat/' + data.receiverId, editDto)
                break;
            case "report":
                if (data.report === "delivered") {
                    functions.setDelivered(data.serverId)
                } else if (data.report === "deleted") {
                    functions.removeMessage(data.serverId)
                }
                let reportDto = {
                    "report": data.report,
                    "id": data.serverId,
                    "type":"report",
                    "remoteMessageID": data.remoteMessageID
                };
                io.emit('/topic/chat/' + data.receiverId, reportDto)
                break;
            case "message":
                functions.saveMessage(data).then(response => {
                    // functions.sendEncryptedMessageNotification(response)
                    io.emit('/topic/chat/' + data.receiverId, response);
                });
                break;
            default:
                console.log("received unknown type");
        }
    } else {
        functions.saveMessage(data).then(response => {
            // functions.sendEncryptedMessageNotification(response)
            io.emit('/topic/chat/' + data.receiverId, response);
        });
    }
});


client.on('/app/conversation/read', (data) => {
    functions.markAsRead(data, userId).then(r => {
        let response = { conversationId: data.conversationId, userId: userId, messagesSeenAt: Date.now() };
        console.log("emitting to /topic/seen/" + r);
        io.emit('/topic/seen/' + r, response);
    });
});

client.on('/app/screenshot', (data) => {
    console.log('User took a screenshot.');
    let dto = {
        userId: userId,
        message: 'The user with the given ID took a screenshot of the conversation.'
    };
    functions.sendScreenShotTakenNotification(userId, data.userId);
    io.emit('/topic/screenshot/' + data.userId, dto);
});

client.on('/app/typing', (data) => {
    let dto = { userId: userId };
    io.emit('/topic/typing/' + data.userId, dto);
});

// client.on('/app/conversation/error', (data) => {
//     let response = { errorId: data.errorId, userId: userId };
//     io.emit('/topic/errors/' + data.userId, response);
// });

client.on('disconnect', () => {
    functions.changeOnlineStatus(userId, false);
    let userDTO = { id: userId, onlineStatus: false };
    io.emit('/topic/online-status', userDTO);
});

client.on('/app/call', (data) => {
    let response = { userId: userId };
    apn.sendVoIPNotification(userId);
    io.emit('/topic/call/' + data.userId, response);
});

client.on('/app/signaling-message', (data) => {
    console.log('Sending signaling message ...');
    const dto = {
        type: data.type,
        title: data.title,
        sessionSDP: data.sessionSDP,
        candidateSDP: data.candidateSDP,
        candidateSDPMLineIndex: data.candidateSDPMLineIndex,
        candidateSDPMid: data.candidateSDPMid,
        userId: userId,
        receiverUserId: data.userId,
        time: Date.now()
    };
    if (data.type === 'offer') {
        functions.fetchInCallStatus(data.userId).then(response => {
            // functions.sendEncryptedMessageNotification(response)
            console.log('GOT RESPONSE:', response)
            if (response.status === true) {
                console.log('GOING INTO IF')
                const busyResponse = {
                    type: 'busy',
                    userId: parseInt(data.userId),
                    receiverUserId: userId
                };
                io.emit('/topic/signaling-message/' + userId, busyResponse);
            } else {
                apn.sendVoIPNotification(dto);
                io.emit('/topic/signaling-message/' + data.userId, dto);
            }
        });
    } else {
        io.emit('/topic/signaling-message/' + data.userId, dto);
    }
});

client.on('/app/is-in-call', (data) => {
    functions.changeInCallStatus(data);
})});

服务器设置代码:

const server = require('http').createServer(app);
const io = require('socket.io')(server);
app.set('socketIo', io);
server.listen(port, (err) => {
   process.setMaxListeners(0)
   console.log('Application running on port ' + port);
});

这是一个 node.js + socket.io 的即时通讯应用。我经常收到此错误。我将 maxListeners 设置为 0 但由于某种原因仍然出现相同的错误......有什么办法解决这个问题吗?谢谢!

【问题讨论】:

    标签: javascript node.js sockets socket.io backend


    【解决方案1】:

    我发现将我的发射器功能移到 io.on('connection') 主体之外,我不再收到错误。事实上,出于我的目的,在将我的代码移到括号外之后,事件处理程序是完全没有必要的。在您使用client 的地方,只需将这些引用更改为io

    【讨论】:

    • 能否提供代码示例?我也面临同样的问题
    猜你喜欢
    • 1970-01-01
    • 2015-03-23
    • 1970-01-01
    • 2023-03-30
    • 2023-01-14
    • 2013-02-16
    • 1970-01-01
    • 2020-04-29
    • 2017-09-06
    相关资源
    最近更新 更多