3

I'm using EventMachine + em-http-request to request Twitter streaming API. It works perfectly, but now I would like to get it error proof.

What would be the best way to detect that the connection is stalled? (in order to try an auto-reconnect).

I have a temporary solution: each time I receive a new chunk from the stream method, I save the current timestamp. A PeriodicTimer is checking this timestamp and issues a reconnection whenever the last-timestamp is more than 30secs old. The issue with this solution is that it makes no difference between a stalled connection and a working connection with no content.

Thanks for your help.

Chris
  • 2,744
  • 3
  • 24
  • 39
  • 1
    Since your are using http which uses TCP connections you should be notified when a disconnect occurs. I am not sure how em-hhtp-request handles it but I am sure it does, just do some tests with a local server. – Schmurfy Feb 14 '12 at 15:14

1 Answers1

3

You can attach an errback callback to your request object:

http.errback { puts 'error or timeout' }

From the em-http-request wiki:

Errback function is invoked only in the case of a failed connection such as a timeout or bad DNS hostname.

Personally, I prefer to use Faraday rather than working with the raw em-http-request library:

require 'faraday'

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

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

Here's a tutorial for Faraday. And if you're working with the twitter streaming API, here's a gotcha to watch out for. Good luck!

gmcnaughton
  • 2,233
  • 1
  • 21
  • 28
Jerry C.
  • 496
  • 5
  • 8