javascript io.sockets.on() 之外的 socket.send

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8281382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:54:14  来源:igfitidea点击:

socket.send outside of io.sockets.on( )

javascriptsocketsnode.jsexpresssocket.io

提问by Nyxynyx

I have a loop that querys a database continuously. When the query returns a result, the node.js app will send a message to every client connected to the node server via socket.io v0.8.

我有一个连续查询数据库的循环。当查询返回结果时,node.js 应用程序将通过 socket.io v0.8 向连接到节点服务器的每个客户端发送一条消息。

Problem:io.sockets.broadcast.send('msg')is called in the middle of a setInterval()loop so it is not within an io.sockets.on()'s callback function and thus this will not work. When io.sockets.send('msg')is used, no message seems to be sent to the client.

问题:io.sockets.broadcast.send('msg')setInterval()循环中间调用,因此它不在io.sockets.on()的回调函数内,因此这将不起作用。当io.sockets.send('msg')使用时,没有消息似乎被发送到客户端。

Node.js code

Node.js 代码

setInterval(function() {
    util.log('Checking for new jobs...');
    dbCheckQueue(function(results) {
        if (results.length) {
            io.sockets.broadcast.send('hello');
        }
    });
}, 10*1000);

However, if the setIntervalis to be called from within io.sockets.on('connection',..), every connected client will create an additional loop!

但是,如果setInterval要从内部调用io.sockets.on('connection',..),则每个连接的客户端都会创建一个额外的循环!

Node.js code

Node.js 代码

io.sockets.on('connection', function(socket) {
    setInterval(function() {
        util.log('Checking for new jobs...');
        dbCheckQueue(function(results) {
            if (results.length) {
                io.sockets.send('hello');
            }
        });
    }, 10*1000);
});

Clientside JS

客户端JS

        socket.on('hello', function() {
            console.log('HELLO received');
        })

*How can I get a SINGLE loop to run, but still be able to send a message to all connected clients?

*如何让单循环运行,但仍然能够向所有连接的客户端发送消息?

回答by Nyxynyx

I think that this will successfully solve your problem

我认为这将成功解决您的问题

io.sockets.emit('hello')