Socket.io issues duplicate data after browser update

I have a page with a button. When a button is pressed, it receives data through socket.io. However, every time I reload the page, socket.io will send back one extra copy of the data from the previous data set. Thus, my data will look good when the page loads (example: abcd). Then reload the page, return 2n data (abcdabcd), reload the page again. I get 3n data (abcdabcdabcd), etc.

How to avoid duplication of data sent back to the client when the page reloads? Here is my code.

Server side:

app.get('/test', function(req, res){

        // some code...

    io.sockets.on("connection", function(socket){

        var socketFn = function(data){
            socket.emit("trends", {
                trends: JSON.parse(redisData)
            });
        };

        socket.on("action", socketFn);

        socket.on("disconnect", function(){
            socket.removeListener("action", socketFn); // this doesn't work
        });

    });
    res.render('test');

});

Client side:

    var socketOpts = {
    "sync disconnect on unload" : true
};
var socket = io.connect("", socketOpts);

socket.on("trends", function(data){
    // data received from the node server, so do something with it
});


function action(){
    socket.emit("action", {phrase: "some dummy data"});
    return false;
}

// already checked client side doesn't fire multiple click event
$("button#click").off("click").on("click", action); 
+4
source share
1 answer

, , .

app.get('/test', function(req, res){
//when client opens the page 

    io.sockets.on("connection", function(socket){
    //start listening to new connection
    ...

eventlisteners . . , , , .

+3

Source: https://habr.com/ru/post/1525762/


All Articles