Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Haskell: Hello World client and server #140

Merged
merged 1 commit into from
Oct 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
---