socket.io setinterval way

后端 未结 2 637
[愿得一人]
[愿得一人] 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:41

    That's pretty much the standard way to do it. If you've not already looked the example apps page on socket.io, there's a beibertweet example that does just this using setInterval.

    Also there's a slightly more advanced example on this blog.

    Plus .. I found Ryan Dahls's intro on YouTube really useful for understanding the basics of node operation.

    Hope that helps.

    0 讨论(0)
  • 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);
    });
    
    0 讨论(0)
提交回复
热议问题