It can be useful in several scenarios if a web application can return data to the browser in a stream, sending data as it becomes available, rather than building up the whole body first and then sending it back in one burst. Examples include:
- Returning progress information for long-running requests
- Proxy applications (where the proxied data is of arbitary size)
- Screen updates using x-multipart-replace
- Any time you want to send a large amount of data back, but X-sendfile isn't appropriate
This is easy to do with a traditional CGI, for example:
#!/usr/bin/ruby -w
$stdout.sync = true
puts "Content-Type: text/html"
puts
puts "<html>", " " * 256
puts "<body>"
(1..10).each do |i|
puts "<p>#{i}</p>"
sleep 1
end
puts "</body></html>"
It would be a plus point to the merb framework if it was able to do this (assuming that the underlying mongrel server allows it).
I tried to do it by creating a socket pair, returning one end of this from the controller, and pumping data into it from another thread:
==> dist/app/controllers/hello.rb <==
require 'thread'
require 'socket'
class Hello < Application
def world
inp, out = Socket.pair("PF_UNIX","SOCK_STREAM",0)
inp.sync = true
out.sync = true
Thread.new(out) do |o|
o.puts "<html>#{" " * 256}"
o.puts "<body>"
(1..10).each do |i|
o.puts "<p>#{i}</p>"
sleep 1
end
o.puts "</body></html>"
o.close
end
return inp
end
end
However, testing this seems to show that all the output is buffered and returned as a single burst after 10 seconds.
telnet localhost 4000
GET /hello/world HTTP/1.0
<blank line>