In my case, Socket.io acts very unstably. It is needed to make it more debuggable and stable.
Introduction
There is a Node'js based backend (Strapi CMS), wherein bootstrap.js I have a right to run my custom code - in my case the socket server:
module.exports = async () => {
process.nextTick(() =>{
var io = require('socket.io')(strapi.server);
io.on('connection', async function(socket) {
console.log(`a user connected`)
// send a message on user connection
socket.emit('question', {message: await strapi.services.question.findOne({ id: 1 })});
//Send a message after a timeout of 4seconds
setTimeout(function() {
socket.emit('endEvent', { description: 'A custom event named EndEvent!'});
}, 4000);
// listen for user diconnect
socket.on('disconnect', () =>{
console.log('a user disconnected')
});
});
strapi.io = io; // register socket io inside strapi main object to use it globally anywhere
})
};
This server is expected to send a question from the database to the socket via custom event -question. The frontend runs with ReactJS. Whenever the page is loaded the socket is created, it establishes a connection with the server and receives the question event from the server, and the data of the quiz question, which is printed as an object.
import React, { useState, useEffect } from "react";
import io from "socket.io-client";
const ENDPOINT = "http://localhost:1337";
const socket = io(ENDPOINT);
function Question() {
const [questionID,setQuestionID] = useState(0)
useEffect(() => {
socket.on('message', (data)=> {setResponse(data)});
socket.on('endEvent', ()=>{console.log('End event done.')})
socket.on('question', (msg, cb) => {
console.log( msg.message)
});
// CLEAN UP THE EFFECT
return () => socket.disconnect();
}, [questionID]);
return(<p>The question debugable from console</p>);
}
export default Question;
Problem.
When I refresh the page, the console.log( msg.message) does print on time, but not each time. Sometimes it just prints when some other component of React is being triggered. For detailed info please see screenshots. This is expected:

It prints the object of question and also End event done. Which is triggered by the server in 4 seconds right after the connection. Instability shows itself when both of the commands run twice, or the object of the question itself delays to display anyhow.
I am not sure if the question is not being sent from the server or it is not printed in the console on client-side... The useEffect() is loaded at first, then triggered each time whenever questionID is changed.
Unexplained behavior
When the countdown time component triggers that the time is expired, you may mention that the 2 important commands of printing and 4 seconds session delay are somehow triggered, which is unexplainable for me, how two independent components of ReactJS may "not fit".
On the server-side, I receive information "connected" and "disconnected" when refreshed. Please comment if an update is needed or have a suggestion for a better title.