Using callbacks with Socket IO

こ雲淡風輕ζ 提交于 2019-12-11 16:17:08

问题


I'm using node and socket io to stream twitter feed to the browser, but the stream is too fast. In order to slow it down, I'm attempting to use setInterval, but it either only delays the start of the stream (without setting evenly spaced intervals between the tweets) or says that I can't use callbacks when broadcasting. Server side code below:

function start(){

stream.on('tweet', function(tweet){

if(tweet.coordinates && tweet.coordinates != null){
    io.sockets.emit('stream', tweet);
    }       

});
}

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

   setInterval(start, 4000);

    });

回答1:


I think you're misunderstanding how .on() works for streams. It's an event handler. Once it is installed, it's there and the stream can call you at any time. Your interval is actually just making things worse because it's installing multiple .on() handlers.

It's unclear what you mean by "data coming too fast". Too fast for what? If it's just faster than you want to display it, then you can just store the tweets in an array and then use timers to decide when to display things from the array.

If data from a stream is coming too quickly to even store and this is a flowing nodejs stream, then you can pause the stream with the .pause() method and then, when you're able to go again, you can call .resume(). See http://nodejs.org/api/stream.html#stream_readable_pause for more info.



来源:https://stackoverflow.com/questions/28121580/using-callbacks-with-socket-io

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!