【问题标题】:EventMachine/em-http-request Detect when http stream connection is stalledEventMachine/em-http-request 检测 http 流连接何时停止
【发布时间】:2012-02-23 04:26:19
【问题描述】:

我正在使用 EventMachine + em-http-request 来请求 Twitter 流 API。 它工作得很好,但现在我想得到它的错误证明。

检测连接停止的最佳方法是什么? (为了尝试自动重新连接)。

我有一个临时解决方案:每次我从流方法收到一个新块时,我都会保存当前时间戳。 PeriodicTimer 正在检查此时间戳,并在最后一个时间戳超过 30 秒时发出重新连接。此解决方案的问题在于,停止连接和没有内容的工作连接没有区别。

感谢您的帮助。

【问题讨论】:

  • 由于您使用的是使用 TCP 连接的 http,因此您应该在发生断开连接时收到通知。我不确定 em-hhtp-request 是如何处理它的,但我确信它可以,只需使用本地服务器进行一些测试。

标签: ruby twitter eventmachine http-streaming


【解决方案1】:

您可以将errback 回调附加到您的请求对象:

http.errback { puts 'error or timeout' }

来自 em-http-request wiki:

只有在连接失败的情况下才会调用 Errback 函数,例如超时或错误的 DNS 主机名。

就我个人而言,我更喜欢使用 Faraday 而不是使用原始的 em-http-request 库:

require 'faraday'

http = Faraday.new do |b|
  b.adapter :em_http
end

res = http.get 'http://whatcodecraves.com'
puts res.body

这是tutorial for Faraday。如果您正在使用 twitter 流 API,请注意here's a gotcha。祝你好运!

【讨论】:

    猜你喜欢
    • 2011-12-12
    • 2012-11-16
    • 2016-09-10
    • 2019-06-11
    • 2012-05-31
    • 1970-01-01
    • 2012-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多