【问题标题】:socket.send outside of io.sockets.on( )socket.send 在 io.sockets.on() 之外
【发布时间】:2012-01-07 01:24:16
【问题描述】:

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

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

Node.js 代码

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

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

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

客户端 JS

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

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

【问题讨论】:

  • io.sockets 可以在io.sockets.on 之外访问。
  • 您只能在socket 上使用broadcast,例如socket.broadcast.sendio.sockets.on-回调中。但是我认为您可以使用io.sockets.send(使用io. 而没有broadcast)发送给所有客户。
  • 哼。如果你想使用socket.on('hello',...),你必须使用socket.emit而不是socket.send
  • 只需使用io.sockets.emit('hello') 发送消息。 socket.io/#how-to-use
  • @Eliasdx 太棒了,行得通。

标签: javascript sockets node.js express socket.io


【解决方案1】:

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

io.sockets.emit('hello')

【讨论】:

  • 谢谢!你拯救了我的一天。
【解决方案2】:

改进@Nyxynyx之前的回答

io.sockets.emit('hello')

相当于:

io.of('/').emit('hello');

如果您需要不同的路由,请更改of 函数参数。

文档: https://socket.io/docs/v3/server-api/index.html#server-sockets

【讨论】:

  • 对于未来的任何人:io.of('/').emit('hello'); 实际上是使用 redis 适配器和房间时更好的功能:io.of('/').adapter.remoteJoin(user.socket_id, data.conversation.id);。原因是io.sockets 将为每个加入房间的人发射。
猜你喜欢
  • 1970-01-01
  • 2014-08-27
  • 2014-08-07
  • 1970-01-01
  • 2012-07-14
  • 1970-01-01
  • 1970-01-01
  • 2019-10-09
相关资源
最近更新 更多