Book Image

Haskell Data Analysis Cookbook

By : Nishant Shukla
Book Image

Haskell Data Analysis Cookbook

By: Nishant Shukla

Overview of this book

Table of Contents (19 chapters)
Haskell Data Analysis Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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…"
        sockHandler sock
  3. Define the handler to process each message received:

    sockHandler :: Socket -> IO ()
    
    sockHandler sock = do
        (h, _, _) <- accept sock
        putStrLn "Connected!"
        hSetBuffering...