Basic `listenOn` HTTP server "Recv failure: Connection reset by peer"
<p>While diving into Haskell's <code>Network</code> library, I'm making a very simple HTTP server based on info from <a href="https://wiki.haskell.org/Simple_Servers" rel="nofollow">this link</a>.</p>

<pre><code>import Control.Concurrent
import Control.Monad
import Network
import System.IO

main = withSocketsDo $ listenOn (PortNumber 8080) &gt;&gt;= loop

loop :: Socket -&gt; IO ()
loop sock = do
  (h,_,_) &lt;- accept sock
  forkIO $ handleRequest h
  loop sock

handleRequest :: Handle -&gt; IO ()
handleRequest h = do
  hPutStr h $ httpRequest "Pong!\n"
  hFlush h
  hClose h

httpRequest :: String -&gt; String
httpRequest body = "HTTP/1.0 200 OK\r\n"
  ++ "Content-Length: " ++ (show.length) body ++ "\r\n"
  ++ "\r\n" ++ body ++ "\r\n"
</code></pre>

<p>However, even though I manage to get some response, the handles seems to be closed unexpectedly soon (sometimes?) as curl tells me:</p>

<pre><code>$ curl localhost:8080
Pong!
curl: (56) Recv failure: Connection reset by peer
</code></pre>

<p><em>NB: Sometimes I don't even get the message (<code>Pong!</code>) or just a part of it. Sometimes, it works... but if I run 100 <code>curl</code>s in a row I eventually get some connection resets.</em></p>

<p>Why is the connection reset? I tried with and without <code>forkIO</code> without success. Have I missed some essential about IO streams in Haskell? Thanks!</p>

<p><em>OS: recent Ubuntu ; GHC: 7.8.4</em></p>

<p><strong>--- Edit: ---</strong></p>

<p>jozefg identified that the problem came from draining the request's contents! However I'd like to send this content back to the client and it hangs while using the following code:</p>

<pre><code>handleRequest :: Handle -&gt; IO ()
handleRequest h = do
  contents &lt;- getHandleContents h
  hPutStr h $ httpRequest contents
  hFlush h
  hClose h

getHandleContents :: Handle -&gt; IO String
getHandleContents h = do
  iseof &lt;- hIsEOF h
  if iseof
    then return []
    else do
      newLine &lt;- hGetLine h
      nextLines &lt;- getHandleContents h
      return $ newLine ++ '\n' : nextLines
</code></pre>

<p>Moreover I had no success draining the whole contents using <code>hGetContents</code>. Any idea why?</p>