require 'socket'
require 'thread'                                                 # <================
def pipeThread(s,r,q,sym)
  Thread.start(s,r){ |s,r| 
    loop do
      d=s.recv(1000000)
      q <<[sym,d]                                                # <================
      Thread.exit if !d || d.size=0
      r.write d
    end
  }
end
gs=TCPServer.new(80)
Thread.start { loop { sleep 0.1 } } # for windows
loop do
  Thread.start(gs.accept) { |s|
    begin
      q=Queue.new                                                # <================
      cs =TCPSocket.new("www.ruby-lang.org",80)
      thg = [pipeThread(s,cs,q,:send),pipeThread(cs,s,q,:recv)]  # <================
      thg << Thread.start(q){ |q| p q.pop } # analyze            # <================
      sleep 0.1 while thg[0].alive? && thg[1].alive?
    ensure
      thg.each {|th| th.kill}
      s.close
      cs.close
      sleep 0.1 until q.empty?                                   # <================
      analyze.kill                                               # <================
    end
  }
end

[:send, "GET / HTTP/1.1\r\nHost: localhost\r\nUser-Agent: Mozilla/5.0 (Windows;
U; Windows NT 5.1; ja; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6\r\nAccept: tex
t/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,ima
ge/png,*/*;q=0.5\r\nAccept-Language: ja,en-us;q=0.7,en;q=0.3\r\nAccept-Encoding:
 gzip,deflate\r\nAccept-Charset: Shift_JIS,utf-8;q=0.7,*;q=0.7\r\nKeep-Alive: 30
0\r\nConnection: keep-alive\r\nCache-Control: max-age=0\r\n\r\n"]
[:recv, "HTTP/1.1 200 OK\r\nDate: Fri, 25 Aug 2006 20:29:10 GMT\r\nServer: Apach
e/2.0.54 (Debian GNU/Linux) mod_ruby/1.2.4 Ruby/1.8.2(2005-04-11) mod_ssl/2.0.54
 OpenSSL/0.9.7e\r\nContent-Length: 591\r\nKeep-Alive: timeout=15, max=100\r\nCon
nection: Keep-Alive\r\nContent-Type: text/html\r\n\r\n\n\n \n  Index of /\n
.
.
.