简体   繁体   English

在 socket.io 中每秒发射一次不起作用

[英]Emitting at every second in socket.io don't work

I have a node.js server, on which a socket.io is supposed to emit something every second.我有一个 node.js 服务器,一个 socket.io 应该每秒发出一些东西。 But at the client side, the clients get the data more than every 30 seconds.但是在客户端,客户端每 30 秒就会获得一次数据。 Anybody has any idea why this is happening and what's the solution?任何人都知道为什么会发生这种情况以及解决方案是什么?

var redis = require("redis"),
    client = redis.createClient();    
const nsp_page=io.of('/myPage');

nsp_page.on('connection', function(socket){
    (function update_index() {
            client.get('boxIndex', function (err, data) {
                socket.emit('boxIndex',data);
            });
        setTimeout(update_index,1000);
    })();
});

Thanks谢谢

But at the client side, the clients get the data more than every 30 seconds.但是在客户端,客户端每 30 秒就会获得一次数据。 Anybody has any idea why this is happening and what's the solution?任何人都知道为什么会发生这种情况以及解决方案是什么?

Because your code sends the data every second.因为您的代码每秒发送一次数据。 This line of code:这行代码:

setTimeout(update_index,1000);

Causes it to call udpate_index() every second, not every 30 seconds.导致它udpate_index()调用udpate_index() ,而不是每 30 秒。 If you want it to update every 30 seconds, you would change that to this:如果您希望它每 30 秒更新一次,您可以将其更改为:

setTimeout(update_index, 30 * 1000);

But, note that the way your code works is very inefficient because you're calling the exact same client.get() for every single connected client.但是,请注意,您的代码的工作方式非常低效,因为您为每个连接的客户端调用完全相同的client.get() That's really inefficient.那真是效率低下。 It would make more sense to call client.get() once and then broadcast that data to every connected client:调用client.get()一次然后将该数据广播到每个连接的客户端会更有意义:

const redis = require("redis");
const client = redis.createClient();    
const nsp_page = io.of('/myPage');

setInterval(() => {
    client.get('boxIndex', function (err, data) {
        if (err) {
            console.log("boxIndex not found", err);
        } else {
            // send to all connected clients
            nsp_page.emit('boxIndex', data);
        }
    });
}, 30 * 1000)

When you have lots of connected clients, this will do only one query of your redis database every 30 seconds and use that result for all clients instead of calling redis separately for every single connected client.当您有很多连接的客户端时,这将每 30 秒只查询一次 redis 数据库,并将该结果用于所有客户端,而不是为每个连接的客户端单独调用 redis。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM