I'm trying to make little ruby script which receives streamed data with a HTTP Chunked Transfer encoding. So I'm using ruby at the client end of this. I can find lots of questions and info about ruby (and rails) serving streams, but not much about consuming them. Maybe because it's trivial, and should just work as a low level feature of HTTP. So can someone give me a little sample script?
I tried a couple of things. This one using open-uri:
require 'open-uri'
streamURL = 'http://localhost/sample-stream.php'
puts "Opening"
open(streamURL) do |f|
puts "Opening steam " + streamURL + " (never gets here)"
p f.meta
p "Content-Type: " + f.content_type
p "last modified" + f.last_modified.to_s
no = 1
# print the first three lines
f.each do |line|
print "#{no}: #{line}"
no += 1
break if no > 4
end
end
...and this one using net http :
require 'net/http'
require 'uri'
streamURL = 'http://localhost/sample-stream.php'
url = URI.parse(streamURL)
full_path = (url.query.empty?) ? url.path : "#{url.path}?#{url.query}"
the_request = Net::HTTP::Get.new(full_path, {'Transfer-Encoding' => 'chunked', 'content-type' => 'text/plain'})
#(Side question: Does it even make sense to specify 'chunked' in the request?)
puts "Opening stream " + streamURL
the_response = Net::HTTP.start(url.host, url.port) { |http|
http.request(the_request)
}
puts the_response.body #never gets here
In both cases it never outputs anything, and I can see in apache my php script is busily spewing more and more data. I think it's clear what's going wrong here. In both cases I think my script is waiting to get the whole response (which will never happen) before processing it.
I should mention that there may be something wrong with my php script (the server), but I can see it blowing its chunks quite nicely into firefox.
So is there an easy ruby way to stream in the data? or should I expect to need special gems/libraries to do this? (I came across this library for example)