Last active
August 29, 2015 13:56
-
-
Save hcarvalhoalves/9313500 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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