【问题标题】:How to break setinterval in io sockets - Nodejs如何打破 io 套接字中的 setinterval - Nodejs
【发布时间】:2019-03-25 17:36:26
【问题描述】:

有一个 api 发送一些 json 数据。nodejs 服务器获取这个 json 数据并每 5 秒向客户端发送一次 websocket。如果在客户端连接时连接处于打开状态,但当客户端断开连接时,它不会停止。

代码

io.on('connection', function(client) {  
        var loop=setInterval(()=>{
            console.log('Client connected...');

            fetch('https://www.foo.com/api/v2/searchAssets')
            .then(res => res.json())
            .then(json => 
            {client.emit('news'{json});console.log(json)}),5000);

        })});

io.on('disconnetion',function(){
                clearInterval(loop);
                console.log("disconnected");
            })

除了 websocket 之外,您还有什么其他建议可以将此 json 数据发送到客户端吗?

提前感谢您的支持

【问题讨论】:

标签: javascript node.js websocket io-socket


【解决方案1】:

您的问题是范围问题。当您声明loop var 时,它是on connection 事件回调的本地变量,在on disconnect 事件中不存在。根据如何handle disconnection 的文档,您可以像这样在连接处理程序中移动断开处理程序:

io.on('connection', function(client) {
  // Start the interval
  var loop = setInterval(()=>{
    console.log('Client connected...');

    fetch('https://www.foo.com/api/v2/searchAssets')
      .then(res => res.json())
      .then(json => {
        client.emit('news'{json});console.log(json)
      } ,5000);
  });

  // Handles disconnection inside the on connection event
  // Note this is using `client.on`, not `io.on`, and that
  // your original code was missing the "c" in "disconnect"
  client.on('disconnect', () => {
    clearInterval(loop);
    console.log("disconnected");
  });
});

但我不推荐这种架构,因为流数据独立于客户端。数据可以一次获取并流式传输给所有人。以下是你可以做到的:

var loop

// The function startStreaming starts streaming data to all the users
function startStreaming() {
  loop = setInterval(() => {
    fetch('https://www.foo.com/api/v2/searchAssets')
      .then(res => res.json())
      .then(json => {
        // The emit function of io is used to broadcast a message to
        // all the connected users
        io.emit('news', {json});
        console.log(json);
      } ,5000);
  });
}

// The function stopStreaming stops streaming data to all the users
function stopStreaming() {
  clearInterval(loop);
}

io.on('connection',function() {
  console.log("Client connected");

  // On connection we check if this is the first client to connect
  // If it is, the interval is started
  if (io.sockets.clients().length === 1) {
    startStreaming();
  }
});

io.on('disconnetion',function() {
  console.log("disconnected");

  // On disconnection we check the number of connected users
  // If there is none, the interval is stopped
  if (io.sockets.clients().length === 0) {
    stopStreaming();
  }
});

【讨论】:

  • 感谢您的回复。您的代码块是否设置了属于每个用户的间隔?提前致谢
  • @digging 是的,它已在此代码部分 // Start the interval intervals[client.id] = ... 中完成。 client.id 用于为每个客户端设置间隔
  • @digging - 你在使用the API Baboo_ 上面的链接吗?
  • @T.J.Crowder 它不能被移动到里面,因为它将是回调的本地。不过可以变成地图
  • 我检查并尝试了您的两个代码块。它们都可以工作,上面的代码块工作正常。谢谢
猜你喜欢
  • 2016-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-27
  • 2021-07-02
  • 1970-01-01
  • 1970-01-01
  • 2014-01-03
相关资源
最近更新 更多