socket.io setinterval way

后端 未结 2 653
[愿得一人]
[愿得一人] 2020-12-30 13:19

I want to make a web page for give the client the news of his friends every 1 second using socket.io + node.js.

My codes :

Client :

<
2条回答
  •  佛祖请我去吃肉
    2020-12-30 13:56

    There is no need for the client to ask for news. You can force the server if you want to emit every 1 second - as long as there are clients connected, they will receive updates. If there are no clients connected, you will see in the logs that nothing happens.

    On the server

    setInterval(function(){
        socket.emit('news_by_server', 'Cow goes moo'); 
    }, 1000);
    

    On the client

    socket.on('news_by_server', function(data){
      alert(data);
    });
    

提交回复
热议问题