/ Published in: Haskell
very basic example to connect/listen/accept on a port.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
import Network.Socket import Network.BSD import Control.Concurrent (forkIO) import Control.Exception (finally) connectTo host port_ = do sock <- socket AF_INET Stream 0 addrs <- liftM hostAddresses $ getHostByName host handle <- socketToHandle sock ReadWriteMode return handle listenAt port_ f = do lsock <- socket AF_INET Stream 0 bindSocket lsock $ SockAddrInet port iNADDR_ANY listen lsock sOMAXCONN loop lsock `finally` sClose lsock where loop lsock = do (sock,SockAddrInet _ _) <- accept lsock handle <- socketToHandle sock ReadWriteMode f handle loop lsock server = withSocketsDo $ do listenAt 12345 (\h -> forkIO (do putStrLn "connection." hPutStrLn h "Hello, and Goodbye!" client = withSocketsDo $ do h <- connectTo "localhost" 12345 hGetLine h >>= putStrLn hClose h