Last active
July 21, 2016 13:05
-
-
Save songpp/6415930 to your computer and use it in GitHub Desktop.
zeromq and protobuf example by haskell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package notification; | |
option java_package = "meta.phor"; | |
option java_outer_classname = "NotificationMessageProtos"; | |
enum EncryptType { | |
NONE = 0; | |
DYNAMIC_AES = 1; | |
APP_SECRET_AES = 2; | |
} | |
message NotificationMessage { | |
required bytes content = 1; | |
required string id = 2; | |
required fixed64 sendTime = 3; | |
required float version = 4; | |
optional EncryptType encryptType = 5 [default = NONE]; | |
} | |
message EncryptedContent { | |
required bytes content = 1; | |
required string magic = 2; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module ProtobufTest where | |
import System.ZMQ3 | |
import Control.Monad | |
import Data.ByteString.UTF8 as U | |
import Control.Concurrent (threadDelay) | |
import NotificationMessageProtos.NotificationMessage as N | |
import NotificationMessageProtos.EncryptType | |
import Text.ProtocolBuffers.WireMessage (messageGet) | |
import qualified Data.ByteString as ByteString | |
import qualified Data.ByteString.Lazy as LB | |
main :: IO () | |
main = runSub "" "tcp://127.0.0.1:8555" | |
-- topic -> addr | |
runSub :: String -> String -> IO () | |
runSub topic address = withContext $ \ ctx -> | |
withSocket ctx Sub $ \ socket -> | |
subscribe socket (fromString topic) >> | |
connect socket address >> | |
(forever $ recv socket) >> return () | |
where recv socket = receiveMulti socket >>= \bs -> | |
deserializeByProtobuf bs | |
deserialize :: [ByteString] -> IO () | |
deserialize bs = forM_ bs (putStrLn . U.toString) | |
deserializeByProtobuf :: [ByteString] -> IO () | |
deserializeByProtobuf ( topic : content : [] ) = (putStrLn $ "topic: " ++ U.toString topic) >> | |
printMessage content | |
where | |
printMessage content = case messageGet (LB.fromStrict content) of | |
Right (notify, x) | LB.length x == 0 -> putStrLn $ showNotify notify -- :: NotificationMessage) | |
Right (notify, x) | LB.length x /= 0 -> error "Failed to parse the message" | |
Left errorMessage -> error errorMessage | |
showNotify :: NotificationMessage -> String | |
showNotify msg = "content : " ++ (U.toString . LB.toStrict . N.content) msg | |
deserializeByProtobuf xs = deserialize xs | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment