title: Simple HTTP server in Ruby using TCPServer
body: <p>For a school assignment, I am trying to create a simple HTTP server using Ruby and the sockets library.</p>
  
  <p>Right now, I can get it to respond to any connection with a simple hello:</p>
  
  <pre><code>require 'socket'
  
  server = TCPServer.open 2000
  puts "Listening on port 2000"
  
  loop {
    client = server.accept()
    resp = "Hello?"
    headers = ["HTTP/1.1 200 OK",
               "Date: Tue, 14 Dec 2010 10:48:45 GMT",
               "Server: Ruby",
               "Content-Type: text/html; charset=iso-8859-1",
               "Content-Length: #{resp.length}\r\n\r\n"].join("\r\n")
    client.puts headers
    client.puts resp
    client.close
  }
  </code></pre>
  
  <p>This works as expected. However, when I have the server tell me who just connected with</p>
  
  <pre><code>puts "Client: #{client.addr[2]}"
  </code></pre>
  
  <p>and use Chromium (browser) to connect to <code>localhost:2000/</code> (just once), I get:</p>
  
  <pre><code>Client: 127.0.0.1
  Client: 127.0.0.1
  Client: 127.0.0.1
  Client: 127.0.0.1
  </code></pre>
  
  <p>I assume this is Chromium requesting auxiliary files, like <code>favicon.ico</code>, and not my script doing something weird, so I wanted to investigate the incoming request. I replaced the <code>resp = "Hello?"</code> line with</p>
  
  <pre><code>resp = client.read()
  </code></pre>
  
  <p>And restarted the server. I resent the request in Chromium, and instead of it coming back right away, it just hung. Meanwhile, I got the output <code>Client: 127.0.0.1</code> in my server output. I hit the "stop" button in Chromium, and then the server crashed with</p>
  
  <pre><code>server.rb:16:in `write': Broken pipe (Errno::EPIPE)
      from server.rb:16:in `puts'
      from server.rb:16:in `block in &lt;main&gt;'
      from server.rb:6:in `loop'
      from server.rb:6:in `&lt;main&gt;'
  </code></pre>
  
  <p>Obviously, I'm doing something wrong, as the expected behavior was sending the incoming request back as the response.</p>
  
  <p>What am I missing?</p>