首页 > 解决方案 > 为什么我的 io.on 不断被解雇?

问题描述

我一直在尝试在项目中使用 socket.io,但是,我的 io.on 被连续触发。我无法理解为什么它在循环中。正如其他答案所建议的那样,我已经交叉检查了这些版本,它们都是一样的。任何帮助都会很棒。这是服务器的代码:-

io.on('connection', async function(socket){
       //These both lines are being called again and again
        console.log("Test"); 
        socket.emit('new_token');
    });

这将是角度的消费者:

 this.socket.on('new_token', () => {
     // console.log(data);
        this.notifier.notify('warning','Embeded token has been updated. Reloading in 3 seconds. !');
        setTimeout(()=>{
          window.location.reload();
        }, 3000);

    });

标签: node.jsangularsocket.io

解决方案


每次网页加载或重新加载时,都会创建一个新的套接字连接。您在每个连接上发出“new_token”,然后您的侦听器通过 window.location.reload() 重新加载页面,这将再次触发连接事件等等。所以这是一种无限循环,因为你只是来回走动。


推荐阅读