require 'httpkit'
class Streaming
def serve(_request, served)
response = streaming_response
served.fulfill(response)
response.body.write('Doing stuff...')
EM.add_timer(1.0) { response.body.write('More stuff...') }
EM.add_timer(2.0) { response.body.write('Done!') }
EM.add_timer(3.0) { response.close }
end
private
def streaming_response
HTTPkit::Response.new(200,
{ 'Content-Type' => 'application/octet-stream' },
HTTPkit::Body.new)
end
end
HTTPkit.run do
address = '127.0.0.1'
port = HTTPkit.random_port(address)
HTTPkit::Server.start(address: address, port: port,
handlers: [Streaming.new])
response = HTTPkit.request(:get, "http://#{address}:#{port}")
puts response.body.chunks
response.body.closed.on_progress { |chunk| puts chunk }
response.body.each { |chunk| puts chunk }
end