Skip to content

Instantly share code, notes, and snippets.

@hcarvalhoalves
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hcarvalhoalves/9313500 to your computer and use it in GitHub Desktop.
Save hcarvalhoalves/9313500 to your computer and use it in GitHub Desktop.
import System.Environment (getArgs, getProgName)
import System.Exit (exitFailure, exitSuccess)
import System.IO
import Network
import Control.Concurrent
import Text.Read
echoCommand :: Handle -> [String] -> IO ()
echoCommand handle cmd = do
hPutStrLn handle (unwords $ tail cmd)
dispatcher :: Handle -> IO ()
dispatcher handle = do
line <- hGetLine handle
let cmd = words line
case (head cmd) of
("echo") -> echoCommand handle cmd
_ -> do hPutStrLn handle "Unknown command"
dispatcher handle
sockHandler :: Socket -> IO ()
sockHandler sock = do
(handle, _, _) <- accept sock
hSetBuffering handle NoBuffering
forkIO $ dispatcher handle
sockHandler sock
mainFail = do
progName <- getProgName
putStrLn $ "Usage: " ++ progName ++ " port"
exitFailure
mainServe port = do
sock <- listenOn $ PortNumber port
putStrLn $ "Starting at " ++ show port
sockHandler sock
exitSuccess
main = do
args <- getArgs
case args of
[arg] -> do
case readMaybe arg :: Maybe Int of
Just port -> mainServe $ fromIntegral port
Nothing -> mainFail
_ -> mainFail
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment