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:

  1. 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)
  2. 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…" ...

Get Haskell Data Analysis Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.