# Streaming with webrick

**URL:** <https://www.ruby-forum.com/t/streaming-with-webrick/90765>\
**Category:** Ruby\
**Created:** [April 1, 2007, 3:22am UTC](https://www.ruby-forum.com/t/streaming-with-webrick/90765 "2007-04-01T03:22:27Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![RyRyRy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/df788c/32.png) [@RyRyRy](https://www.ruby-forum.com/u/RyRyRy)\
**Post date:** [April 1, 2007, 3:22am UTC](https://www.ruby-forum.com/t/streaming-with-webrick/90765/1 "2007-04-01T03:22:27Z")

</div>

Can someone explain to me why the following serverlet doesn’t stream  
Hellos.

require ‘webrick’

class Streamlet \< WEBrick::HTTPServlet::AbstractServlet  
def do\_GET(req, res)  
res[“content-type”] = “text/plain”  
r, w = IO.pipe  
res.body = r  
res.chunked = true

```
Thread.new do
  5.times do |i|
    w.write("hello #{i}\n")
    sleep(1)
  end
  w.close
end

```

end  
end

@server = WEBrick::HTTPServer.new(:Port =\> 4711)  
@server.mount("/stream", Streamlet)

trap(“INT”) { @server.shutdown }  
@server.start

Thank you.

---

<div class="post-metadata">

**Author:** ![RyRyRy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/df788c/32.png) [@RyRyRy](https://www.ruby-forum.com/u/RyRyRy)\
**Post date:** [April 1, 2007, 7:37am UTC](https://www.ruby-forum.com/t/streaming-with-webrick/90765/2 "2007-04-01T07:37:41Z")

</div>

On Mar 31, 2007, at 18:20, Ry wrote:

> ```
> res.chunked = true
> 
> Thread.new do
> 5.times do |i|
> 
> ```

I believe that 5 isn’t enough hellos to fill up a chunk. Changing  
this to loop do … end causes webrick to give you infinite hellos.

---

<div class="post-metadata">

**Author:** ![RyRyRy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/df788c/32.png) [@RyRyRy](https://www.ruby-forum.com/u/RyRyRy)\
**Post date:** [April 1, 2007, 4:56pm UTC](https://www.ruby-forum.com/t/streaming-with-webrick/90765/3 "2007-04-01T16:56:29Z")

</div>

> I believe that 5 isn’t enough hellos to fill up a chunk. Changing  
> this to loop do … end causes webrick to give you infinite hellos.

Looking at the webrick’s code in httpresponse.rb

261 while buf = @body.read(BUFSIZE)  
262 next if buf.empty?  
263 data = “”  
264 data \<\< format("%x", buf.size) \<\< CRLF  
265 data \<\< buf \<\< CRLF

The servlet reaches line 261 immediately but hangs for 5 seconds  
before getting to line 262. If the IO.pipe only has a bit of data in  
it, it seems like @body.read(BUFSIZE) should only return what is in  
there and not wait for BUFSIZE.

Is there a way to avoid this behavior?

Thanks,  
ry
