Prevent Socket connection from initializing again

173 views Asked by At

I am trying to make a chat app which sends first message as "Hi. there". But due to some some reasons (unstable internet connection might be one) the socket get initialized multiple times and sends the "Hi. there" message multiple times. Below is the code. How to stop the app for sending multiple messages?

io.socket.on('connect', function() {
        /* On successfull connection to server */
        console.log('Connected to server');
        //Some code here
        io.socket.get(url + '/userstatus/subscribe', function(resData, jwres) {
            //Some code here
            io.socket.on("userstatus", function(event) {
                    //Socket updartes
                    // Send Message code at this line.
                }
            }
        });
1

There are 1 answers

1
bolav On

You need to change your client side code, so that it stores state, and sends it to the server on reconnect. That way the server can give the correct response.

Something like this might work:

socket.on('connect', function() {
    /* On successfull connection to server */
    console.log('Connected to server');
    socket.emit('state', state_object);
});