Sunday, August 28, 2011

RealTime and Rails

Sometimes you have a need to process things in real-time. Stock trading apps for example,
or real-time video. EventMachine, in Ruby is great. On top of this you want a gui or a
web page, so Rails naturally fits in. The problem is trying to do Real-Time and Rails in
the same sentence is not quite there. In a application I've done, I had exactly that,
I receive multiple HD cctv feeds in UDP, and handled the whole RTSP protocol using eventmachine.
The problem was every 5 minutes I wanted to save the current file information into
the database. I tried a few methods, but the most reliable turned out to use a em_http request.
This allows you to do async http in eventmachine. I of course targeted my rails stack that
was already running the application.

So this way, my realtime work can continue (async), and the rails stack gets a tickle
every 5 minutes to stay alert. Result: No more dropped packets.
EventMachine.run {
      http = EventMachine::HttpRequest.new('http://gshift-app/').get :query => {'keyname' => 'value'}

      http.errback { p 'Uh oh'; EM.stop }
      http.callback {
        p http.response_header.status
        p http.response_header
        p http.response

        EventMachine.stop
      }
    }


0 comments: