module Main( main ) where

import Network
import IO
import Control.Concurrent

main :: IO ()
main = withSocketsDo $ --For windows compatibility
  do
  theSocket <- listenOn (PortNumber 2048)
  sequence_ $ repeat $ acceptConnectionAndFork
            theSocket
      where
      acceptConnectionAndFork :: Socket -> IO ()
      acceptConnectionAndFork theSocket =
          do
          connection <- accept theSocket
          let (handle, hostname, portnumber ) = connection
          putStr ("("++ hostname ++ ":" ++ (show portnumber) ++ "): Open\n" )
          forkOS (echoServer connection)
          return ()

echoServer :: (Handle, String, PortNumber) -> IO ()
echoServer (handle, hostname, portnumber ) =
  do
  a <- hGetContents handle
  putStr $ foldr (++) "" $ map (\a -> "(" ++ hostname ++ ":" ++ (show portnumber) ++ "): Msg " ++ (show a) ++ "\n" ) $ lines a
  putStr ("("++ hostname ++ ":" ++ (show portnumber) ++ "): Close\n" )
