简体   繁体   中英

Socket.io hang after sending too many request on node server

I am working on a chat application using Node js, socket.io, React js where I am emitting socket event to node server and it calls another API(node js) to save data(message) on DB. when I trying to send messages very quickly, After that the node server hangs and socket disconnects and connects frequently . After sometimes(approx 5 mins) node server works perfectly. Please tell me what I am doing wrong.

Currently, I am testing for only 2 users.

Here is a code snippet.

io.on('RequestSendNewMessage', (message)=>{
        // console.log('message', message);
        headers['wh-user-id'] = message.user_id;
        makeRequest({data: message, method: 'POST', url: `${workstream}/v1/workstream/send-message`, headers})
        .then( async (response) => {
            const message_count = await makeRequest({params: {}, method: 'GET', url: `${workstream}/v1/workstream/message-count`, headers})
            socket.emit('RespondNewMessageCount', message_count.data.data);
            socket.emit('RespondSendNewMessage', response.data);
        })
        .catch(error => {
            console.log('errror', error.response.data);
            socket.emit('newMessageError', error.response.data)
        })

    })

It is highly recommended to use message queuing in these scenarios...As long as you are calling another api's to perform some DB operation, It keeps your node thread busy...

To avoid this, you can store the message in message queuing tool(RabbitMQ)received through socket, and close the connection, by doing this, node thread can be ideally utilized

Later the messages published into RabbitMQ, can be consumed by your worker(separate node server) and it will take care of storing messages into your DB and sending chat messages....As the worker is being influenced by the message QUEUE, it would work one by one (FIFO) message and no mess will take place

Please refer: https://medium.com/better-programming/implementing-rabbitmq-with-node-js-93e15a44a9cc

(Note: It is good to keep the worker as a separate server)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM