Advertisement
Guest User

Untitled

a guest
Oct 16th, 2020
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. module Lib
  2. ( runMDR
  3. ) where
  4.  
  5. import Control.Concurrent (forkFinally)
  6. import qualified Control.Exception as E
  7. import Control.Monad (unless, forever, void)
  8. import qualified Data.ByteString as S
  9. import Data.ByteString.UTF8
  10. import Network.Socket
  11. import Network.Socket.ByteString (recv, sendAll)
  12. import System.IO
  13.  
  14. runMDR :: IO ()
  15. runMDR = runTCPServer Nothing "3000" talk
  16. where
  17. talk h = do
  18. line <- hGetLine h
  19. putStrLn line
  20. talk h
  21.  
  22. -- from the "network-run" package.
  23. runTCPServer :: Maybe HostName -> ServiceName -> (Handle -> IO a) -> IO a
  24. runTCPServer mhost port server = withSocketsDo $ do
  25. addr <- resolve
  26. E.bracket (open addr) close loop
  27. where
  28. resolve = do
  29. let hints = defaultHints {
  30. addrFlags = [AI_PASSIVE]
  31. , addrSocketType = Stream
  32. }
  33. head <$> getAddrInfo (Just hints) mhost (Just port)
  34. open addr = do
  35. sock <- socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)
  36. setSocketOption sock ReuseAddr 1
  37. withFdSocket sock $ setCloseOnExecIfNeeded
  38. bind sock $ addrAddress addr
  39. listen sock 1024
  40. return sock
  41. loop sock = forever $ do
  42. (conn, _peer) <- accept sock
  43. handle <- socketToHandle conn ReadWriteMode
  44. void $ forkFinally (server handle) (const $ gracefulClose conn 5000)
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement