Skip to content

Instantly share code, notes, and snippets.

@wardbekker
Created December 10, 2010 22:28
Show Gist options
  • Save wardbekker/736929 to your computer and use it in GitHub Desktop.
Save wardbekker/736929 to your computer and use it in GitHub Desktop.
start worker node with 'node worker' and start commander with 'node commander'. The commander will send a msg to the worker and the worker will respond with "tnx for the fish!". The worker will wait for new commander msg's indefinitely, so stop with CTRL-
{-# LANGUAGE OverloadedStrings #-}
import qualified System.ZMQ as ZMQ
import Data.Binary
import Data.Binary.Put
import Data.Binary.Get
import Data.ByteString.Lazy as LZ
import Data.ByteString as STR
import Data.Bson
import Data.Bson.Binary
import Data.UString (u)
import Control.Monad (forever)
import System ( getArgs )
main :: IO ()
main = do
context <- ZMQ.init 1
(arg1:_) <- getArgs
launch context arg1
where
launch :: ZMQ.Context -> String -> IO ()
launch context arg =
case arg of
"worker" -> launchWorker context
"commander" -> launchCommander context
otherwise -> error "Please specify worker or commander"
launchWorker :: ZMQ.Context -> IO ()
launchWorker context = do
socket <- ZMQ.socket context ZMQ.Rep
ZMQ.bind socket "tcp://127.0.0.1:5555"
forever $ do
request <- ZMQ.receive socket []
Prelude.putStrLn $ "received msg: " ++ (show $ fromBinaryMsg request)
ZMQ.send socket okMsg []
-- not yet reached- --
ZMQ.close socket
launchCommander :: ZMQ.Context -> IO ()
launchCommander context = do
socket <- ZMQ.socket context ZMQ.Req
ZMQ.connect socket "tcp://127.0.0.1:5555"
ZMQ.send socket commanderMsg []
response <- ZMQ.receive socket []
Prelude.putStrLn $ "response received msg: " ++ (show $ fromBinaryMsg response)
ZMQ.close socket
commanderMsg :: STR.ByteString
commanderMsg = toBinaryMsg "do your job! NOW!"
okMsg :: STR.ByteString
okMsg = toBinaryMsg "Thanks for the fish"
toBinaryMsg :: String -> STR.ByteString
toBinaryMsg msg = STR.concat . toChunks $ lazyStr
where
lazyStr = runPut $ putDocument [(u"msg" =: u msg)]
fromBinaryMsg :: STR.ByteString -> Value
fromBinaryMsg byteMsg = valueAt (u"msg") doc
where
doc = runGet getDocument $ LZ.fromChunks [byteMsg]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment