title: Haskell: Debugging a Multithreaded Server
body: <p>I'm trying to implement a simple network application in haskell. The application is supposed to start two servers that send packets to one another. See the following code:</p>
  
  <pre><code>#!/usr/bin/env runghc
  
  module Main where
  
  import Network
  import System.IO
  import Control.Concurrent.Thread as Thread
  import Control.Arrow
  
  instance Read PortNumber where
    readsPrec p s = map (first fromInteger) $ readsPrec p s
  
  pingpong :: PortNumber -&gt; IO (IO ())
  pingpong port = do
      s &lt;- listenOn $ PortNumber port  -- start server
      print ("listening", "on", port)
      return $ run s                 
    where
      run s = do 
        (h,host,_) &lt;- accept s            -- wait for packet to arrive
        port' &lt;- fmap read $ hGetLine h   -- read dst port from packet
        hClose h
        print ("recved", "from", host, port')
        h &lt;- connectTo host (PortNumber port')  -- send packet back
        print ("connected", "to", port')
        hPutStr h $ show port
        hClose h
        print ("sent", "to", port')
  
  hosts = map pingpong [8080, 8081]
  
  main :: IO ()
  main = withSocketsDo $ do
      servers &lt;- sequence hosts   -- start servers
      print "started servers"
      threads &lt;- mapM Thread.forkIO servers  -- start listeners
      h &lt;- connectTo "localhost" (PortNumber 8080)  -- send initial packet
      hPutStr h $ show 8081
      hClose h
      print "sent initial ping to 8081"
  </code></pre>
  
  <p>Running the above code, the two servers start as expected, a packet is sent, but then the receiver just dies without any sort of error-message.</p>
  
  <pre><code>("listening","on",8080)
  ("listening","on",8081)
  "started servers"
  "sent initial ping to 8081"
  ("recved","from","localhost",8081)
  </code></pre>
  
  <p>Can anyone tell me what is going wrong, or how I can debug the problem? I tried using <a href="https://stackoverflow.com/questions/6009384/exception-handling-in-haskell"><code>catch</code>/<code>handle</code></a> and <a href="http://www.haskell.org/haskellwiki/Debugging#Stack_trace" rel="nofollow noreferrer">stack-traces</a>, but didn't get any valuable additional information.</p>