Communicating in real time through sockets
Sockets provide a convenient way of communicating between programs in real time. Think of them as a chat client.
In this recipe, we will pass messages from one program to another and obtain responses.
How to do it…
Insert the following code in a new file called Main.hs
:
- Create the server code:
import Network ( listenOn, withSocketsDo, accept , PortID(..), Socket ) import System.Environment (getArgs) import System.IO ( hSetBuffering, hGetLine, hPutStrLn , BufferMode(..), Handle ) import Control.Concurrent (forkIO)
- Create a socket connection to listen on, and attach our handler,
sockHandler
, on it:main :: IO () main = withSocketsDo $ do let port = PortNumber 9001 sock <- listenOn port putStrLn $ "Listening…" sockHandler sock
- Define the handler to process each message received:
sockHandler :: Socket -> IO () sockHandler sock = do (h, _, _) <- accept sock putStrLn "...