[Haskell-beginners] TCP Server

Ertugrul Soeylemez es at ertes.de
Mon May 16 15:30:37 CEST 2011


Raphael Päbst <raphael.paebst at googlemail.com> wrote:

> I need a TCP server for my current project and am now wondering if I
> have to write it from scratch or if there is a package out there that
> lets me avoid this. I have seen examples of TCP servers for example in
> the Real World Haskell book, but they are a bit confusing to me at the
> moment, so I'd like to avoid tackling this one.

TCP servers are surprisingly easy to write.  You will want to learn how
to write concurrent programs in Haskell first, then you would just
listen on a port and accept connections in a loop like this:

    import Control.Exception
    import Network
    import System.IO

    handleClient :: Handle -> IO ()
    handleClient h = ...

    server :: IO ()
    server = do
        socket <- listenOn (PortNumber 4000)
        forever $ do
            (h, hostname, port) <- accept socket
            forkIO $ handleClient h `finally` hClose h

This is how it works basically.  Communication between the threads can
be carried out by using concurrency constructs like MVar and/or by using
software transactional memory (STM).  For really elegant concurrent
applications you should also learn how to use STM.

For learning concurrent programming I found the Control.Concurrent
documentation to be sufficient, but YMMV.  For STM you will find good
references in HaskellWiki's STM page.


Greets,
Ertugrul


-- 
nightmare = unsafePerformIO (getWrongWife >>= sex)
http://ertes.de/





More information about the Beginners mailing list