Answer the question
In order to leave comments, you need to log in
Function is executed multiple times, why ( Node JS + Socket IO )?
Friends, hello. Faced such problem that sockets send function several times at the same time.
It is necessary to make it so that it goes 1 time in 3 seconds. Maybe the problem is in setTimeout? ( usersCount() function )
Code example:
io.sockets.on('connection', function(socket){
console.log('connect');
setTimeout(usersCount, 3000);
});
/* Доступ к статистике */
function usersCount() {
connection.query('SELECT COUNT(*) FROM `users`', function(err, rows) {
users = rows['0']['COUNT(*)'];
});
https_server.getConnections(function (err, count) {
online = count;
});
connection.query('SELECT COUNT(*) FROM `drops`', function(err, rows) {
drops_count = rows['0']['COUNT(*)'];
});
var json = {
users: users,
online: online,
drops: drops_count
};
socket.emit('stats',json); // отправим в сокеты
setTimeout(usersCount, 5*3000);
}
Answer the question
In order to leave comments, you need to log in
Figured it out, removed
io.sockets.on('connection', function(socket){
With SetTimeout you don't limit the number of executions per second, you just delay the call by 3 seconds. And if there were 2 connections in a row, then after 3 seconds usersCount will be called 2 times.
You need to perform the send function only if there are connected users and send across all connections (they can be further divided into rooms/groups and send the necessary data for each room).
setIterval(usersCount, 5 * 3000);
function usersCount() {
io.sockets.clients((err, clients) => {
if (err) throw err;
if (clients.length) {
// do some sql
io.sockets.emit('stats', json);
}
});
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question