public
Created

Ping server

  • Download Gist
gistfile1.hs
Haskell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
import System.Environment (getArgs, getProgName)
import Control.Concurrent (forkIO)
import Network (Socket, PortID(PortNumber), withSocketsDo,
listenOn, accept)
import System.IO (hPutStrLn, hGetLine, hFlush)
import Control.Monad (forever)
 
main = withSocketsDo $ do
args <- getArgs
prog <- getProgName
case args of
[port] -> do
socket <- listenOn $ PortNumber (fromIntegral (read port :: Int))
putStrLn $ "Listening for pings on " ++ port
handleRequest socket
_ ->
putStrLn $ "usage: " ++ prog ++ " <port>"
 
handleRequest s = do
(handle, _, _) <- accept s
forkIO $
forever $ do
input <- hGetLine handle
processPing (hPutStrLn handle) (init input)
hFlush handle
handleRequest s
 
processPing f msg = do
case msg of
"ping" -> f "pong!"
_ -> f "Did you mean `ping'?"

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.