Skip to content

Instantly share code, notes, and snippets.

@evanrinehart
Last active August 4, 2017 04:39
Show Gist options
  • Save evanrinehart/962f040683674c141906b0266feb7125 to your computer and use it in GitHub Desktop.
Save evanrinehart/962f040683674c141906b0266feb7125 to your computer and use it in GitHub Desktop.
module Main where
import Network
import Control.Monad (forever)
import Data.Function (fix)
import Control.Exception (try)
import System.IO
import Data.IORef
import Control.Concurrent (forkIO)
main = do
server <- listenOn (PortNumber 1234)
nextClientId <- newIORef 0
forever $ do
(client, _, _) <- accept server
clientId <- readIORef nextClientId
modifyIORef nextClientId (+1)
forkIO (handleConnection client clientId)
handleConnection :: Handle -> Integer -> IO ()
handleConnection client clientId = do
let log x y = putStrLn (show x ++ ": " ++ y)
log clientId "connected"
fix $ \loop -> do
message <- try (hGetLine client) :: IO (Either IOError String)
case message of
Left _ -> log clientId (" client left")
Right msg -> do
log clientId (" received " ++ msg)
hPutStrLn client msg
loop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment