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 = 200response.send_status(nil)response.header['Content-Type'] = "text/plain"response.send_header10.times doresponse.write("Message \r\n")sleep 5endresponse.doneendendMongrel::Configurator.new dolistener :port => 3000 douri "/", :handler => StreamHandler.newendrun; joinend
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 segmentendend
For more information about get_response method and read_body check the ruby documentation.
Comments