在 Socket IO 中使用回调 [英] Using callbacks with Socket IO

查看:40
本文介绍了在 Socket IO 中使用回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 node 和 socket io 将 twitter 提要流式传输到浏览器,但流太快了.为了减慢速度,我尝试使用 setInterval,但它要么只延迟流的开始(没有设置推文之间的均匀间隔),要么说我在广播时不能使用回调.服务端代码如下:

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);

    });

推荐答案

我认为您误解了 .on() 如何用于流.这是一个事件处理程序.安装后,它就在那里,流可以随时给您打电话.您的时间间隔实际上只是让事情变得更糟,因为它安装了多个 .on() 处理程序.

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.

如果来自流的数据太快而无法存储,并且这是一个流动的 nodejs 流,那么您可以使用 .pause() 方法暂停流,然后,当您可以再去,可以调用.resume().请参阅 http://nodejs.org/api/stream.html#stream_readable_pause 了解更多信息.

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.

这篇关于在 Socket IO 中使用回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆