Phantom454
Phantom454

Reputation: 19

How to fix MaxListeners warning in node.js+socket.io? What is wrong with my code?

0|server | (node:22094) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 wakeup listeners added to [Connection]. Use emitter.setMaxListeners() to increase limit

Exact error i'm getting.^

This is my io code:

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

Server setup code:

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

This is a node.js + socket.io instant messaging app. I get this error quite frequently. I set maxListeners 0 but am still getting the same error for some reason... Any way to solve this? Thanks!

Upvotes: 0

Views: 1373

Answers (1)

I found that by moving my emitter functions outside of the io. on('connection') body, I stopped getting the error. In fact, for my purposes, that event handler was completely unnecessary after moving my code outside the brackets. Where you are using client, simply change those references to io.

Upvotes: 1

Related Questions