(Socket.io on nodejs) Updating div with mysql data stops without showing error

- 1 answer

Ad

I'm using socket.io for my new project and I'm totally new at it. After doing a lot of research i could get to the point I want. I have divs dynamically filled with data from mysql. So what I'm doing on my server.js is using setInterval to query the data every second and emit a message(updateItem) to client. My code:

function updateitems(){
pool.getConnection(function(err,connection){
   if (err) {
    console(err);
     connection.release();
     return;
   }
connection.query("SELECT * FROM items",function(err,rows){
       if(!err) {
        var items= [];
        for (var i = 0; i < rows.length; i++) {
            items.push(rows[i]);
        }
        io.sockets.emit('updateItems', items);
        }else{
            console.log(err);
        }

});
connection.on('error', function(err) {
    console.log(err);
    return;
});
});
}

and then:

setInterval(updateitems, 1000);

The thing is, after about 30 or 40 seconds the divs stop updating, the server console doesn't show any error message or anything, the levels on VPS are good, no high load or anything. It just stops... Any advice? Thank You!

Ad

Answer

Ad

Assuming you are using node-mysql or something similar, then you must release your connection when you are done with it so it can go back to the connection pool and be reused. Otherwise, your pool will run out of connections and subsequent requests for a connection will either just stall or make an error. Here's one way you can release the connection:

function updateitems() {
    pool.getConnection(function (err, connection) {
        if (err) {
            console(err);
            connection.release();
            return;
        }
        connection.query("SELECT * FROM items", function (err, rows) {

            // <<<< Add this line >>>>
            connection.release();

            if (!err) {
                var items = [];
                for (var i = 0; i < rows.length; i++) {
                    items.push(rows[i]);
                }
                io.sockets.emit('updateItems', items);
            } else {
                console.log(err);
            }
        });
        connection.on('error', function (err) {
            // <<<< Add this line >>>>
            connection.release();

            console.log(err);
            return;
        });
    });
}
Ad
source: stackoverflow.com
Ad