OpenSource For You

Network Programmin­g in Haskell

Haskell, named after logician Haskell Curry, is a standardis­ed, general-purpose, purely functional programmin­g language, with non-strict semantics and strong static typing. This eleventh article on Haskell covers network programmin­g.

-

Let us begin with a simple TCP (transmissi­on control protocol) client and server example. The network package provides a high-level interface for communicat­ion. You can install the same in Fedora, for example, using the following command:

$ sudo yum install ghc-network

Consider the following simple TCP client code:

-- tcp-client.hs import Network import System.IO main :: IO () main = withSocket­sDo $ do handle <- connectTo “localhost” (PortNumber 3001) hPutStr handle “Hello, world!”

hClose handle

After importing the required libraries, the main function connects to a localhost server running on Port 3001, sends a string ‘Hello, world!’ and closes the connection.

The connectTo function defined in the Network module accepts a hostname, port number and returns a handle that can be used to transfer or receive data.

The type signatures of the withSocket­sdo and connectTo functions are as follows: ghci> :t withSocket­sDo withSocket­sDo :: IO a -> IO a ghci> :t connectTo connectTo :: HostName -> PortID -> IO GHC.IO.Handle.Types. Handle

The simple TCP server code is illustrate­d below:

 ??  ??

Newspapers in English

Newspapers from India