简体   繁体   中英

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

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!

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;
        });
    });
}

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