Skip to content

Commit

Permalink
Merge pull request #140 from sohang3112/master
Browse files Browse the repository at this point in the history
Haskell: Hello World client and server
  • Loading branch information
sappo committed Oct 2, 2023
2 parents bd2cf69 + ad62589 commit 0229fb4
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
---
name: hello_world_server
language: python
library: pyzmq
---

```haskell
-- This lets us conviniently use efficient ByteString to send and recieve messages
{-# LANGUAGE OverloadedStrings #-}

{-
Hello World client in Haskell
Connects REQ socket to tcp://localhost:5555
Sends "Hello" to server, expects "World" back
-}

import System.ZMQ4.Monadic (runZMQ, socket, connect, send, receive, Socket, Req(..))
import Control.Monad (forM_)
import Control.Monad.IO.Class (liftIO)
import Data.ByteString.Char8 (pack, unpack)

main :: IO ()
main = runZMQ $ do
-- Socket to talk to server
reqSocket <- socket Req
connect reqSocket "tcp://localhost:5555"

-- Do 10 requests, waiting each time for a response
forM_ [1..10] $ \i -> do
liftIO $ putStrLn ("Sending request " ++ show i ++ "...")
send reqSocket [] (pack "Hello")

-- Get the reply
message <- receive reqSocket
liftIO $ putStrLn ("Received reply " ++ show i ++ " [" ++ unpack message ++ "]")
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
---
name: hello_world_server
language: python
library: pyzmq
---

```haskell
-- This lets us conviniently use efficient ByteString to send and recieve messages
{-# LANGUAGE OverloadedStrings #-}

{-
Hello World server in Haskell
Binds REP socket to tcp://*:5555
Expects "Hello" from client, replies with "World"
-}

import System.ZMQ4.Monadic (runZMQ, socket, bind, send, receive, Socket, Rep(..))
import Control.Monad (forever)
import Control.Monad.IO.Class (liftIO)
import Control.Concurrent (threadDelay)
import Data.ByteString.Char8 (pack, unpack)

main :: IO ()
main = runZMQ $ do
repSocket <- socket Rep
bind repSocket "tcp://*:5555"
forever $ do
-- Wait for next request from client
message <- receive repSocket
liftIO $ putStrLn ("Received request: " ++ unpack message)

-- Do some 'work' (waiting for 1 second here)
liftIO $ threadDelay (1 * 1000000)

-- Send reply back to client
send repSocket [] (pack "World")
```
3 changes: 3 additions & 0 deletions content/docs/examples/haskell/zeromq4-haskell/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
---
headless: true
---

0 comments on commit 0229fb4

Please sign in to comment.