Created
May 8, 2013 08:01
-
-
Save quchen/5538940 to your computer and use it in GitHub Desktop.
Basic client/server
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 Network | |
import System.IO | |
import Control.Exception | |
main = loop | |
loop :: IO a | |
loop = do | |
putStr "Enter message: " >> hFlush stdout | |
message <- getLine | |
bracket (connectTo "localhost" $ PortNumber 9001) | |
hClose | |
(\h -> hPutStrLn h message) | |
loop |
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 Control.Concurrent | |
import Control.Exception | |
import Network | |
import System.IO | |
main :: IO () | |
main = do | |
putStrLn "Opening socket on port 9001" | |
bracket (listenOn $ PortNumber 9001) sClose loop | |
-- | Listens on a socket and forks a worker thread for incoming connections | |
loop :: Socket -> IO () | |
loop socket = do | |
(h, _, _) <- accept socket | |
forkIO $ worker h | |
loop socket | |
-- | Prints received messages | |
worker :: Handle -> IO () | |
worker h = (`finally` hClose h) $ do | |
message <- hGetLine h | |
putStrLn $ "Received message: " ++ message |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment