HTTP Streaming Ruby Client

Let's say you have a HTTP streaming server such as the one below where the server sends the HTTP response slowly or may it even holds on the request and does not close the connection and keep sending data (so called "HTTP Streaming"). How would you write a client that receives the response segments as soon as they arrive? (we do not want to wait till the whole response ends or we do not have a choice since the server is streaming "infinite" data).


require 'rubygems'
require 'mongrel'

class StreamHandler <>
  def process(request, response)
    response.status = 200
    response.send_status(nil)

    response.header['Content-Type'] = "text/plain" 
    response.send_header

    10.times do
      response.write("Message \r\n")
      sleep 5
    end

    response.done
  end
end

Mongrel::Configurator.new do
  listener :port => 3000 do
    uri "/", :handler => StreamHandler.new
  end
  run; join
end


The client code below lets you access the response segments as soon as they arrive:

require 'net/http'

Net::HTTP.get_response('my-streaming-server', '/stream-path/', 12345) do |response|
response.read_body do |segment|
puts segment
end
end
For more information about get_response method and read_body check the ruby documentation.

Comments

Popular posts from this blog

Accessing Resources in Java, use of getResource method of Class and ClassLoader, How to access test data in unit tests

Comparison of equality operators in Ruby: == vs. equal? vs. eql? vs. ===

TCPView