Networking sample in Haskell


/ Published in: Haskell
Save to your folder(s)

very basic example to connect/listen/accept on a port.


Copy this code and paste it in your HTML
  1. import Network.Socket
  2. import Network.BSD
  3. import System.IO (Handle, IOMode(ReadWriteMode), hPutStrLn, hGetLine, hClose)
  4. import Control.Monad (liftM)
  5. import Control.Concurrent (forkIO)
  6. import Control.Exception (finally)
  7.  
  8. connectTo :: String -> Int -> IO Handle
  9. connectTo host port_ = do
  10. let port = toEnum port_
  11. sock <- socket AF_INET Stream 0
  12. addrs <- liftM hostAddresses $ getHostByName host
  13. if null addrs then error $ "no such host : " ++ host else return ()
  14. connect sock $ SockAddrInet port (head addrs)
  15. handle <- socketToHandle sock ReadWriteMode
  16. return handle
  17.  
  18. listenAt :: Int -> (Handle -> IO ()) -> IO ()
  19. listenAt port_ f = do
  20. let port = toEnum port_
  21. lsock <- socket AF_INET Stream 0
  22. bindSocket lsock $ SockAddrInet port iNADDR_ANY
  23. listen lsock sOMAXCONN
  24. loop lsock `finally` sClose lsock
  25. where
  26. loop lsock = do
  27. (sock,SockAddrInet _ _) <- accept lsock
  28. handle <- socketToHandle sock ReadWriteMode
  29. f handle
  30. loop lsock
  31.  
  32. server = withSocketsDo $ do
  33. listenAt 12345 (\h -> forkIO (do
  34. putStrLn "connection."
  35. hPutStrLn h "Hello, and Goodbye!"
  36. `finally` hClose h) >> return ())
  37.  
  38. client = withSocketsDo $ do
  39. h <- connectTo "localhost" 12345
  40. hGetLine h >>= putStrLn
  41. hClose h

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.