From 3bc9e4bc24bcaa23c4fd92e2282fa46bbcc64f93 Mon Sep 17 00:00:00 2001 From: Xackery Date: Sat, 10 Mar 2018 19:47:02 -0800 Subject: [PATCH] Added python example --- utils/nats/helloworld/README.md | 7 +++++ utils/nats/helloworld/helloworld2.py | 47 ++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 utils/nats/helloworld/README.md create mode 100644 utils/nats/helloworld/helloworld2.py diff --git a/utils/nats/helloworld/README.md b/utils/nats/helloworld/README.md new file mode 100644 index 000000000..a7cbf9b96 --- /dev/null +++ b/utils/nats/helloworld/README.md @@ -0,0 +1,7 @@ +Hello World NATS example + +# helloworld2.py +* run `pip install nats-client` +* run `pip install protobuf` + + diff --git a/utils/nats/helloworld/helloworld2.py b/utils/nats/helloworld/helloworld2.py new file mode 100644 index 000000000..d4b9f8757 --- /dev/null +++ b/utils/nats/helloworld/helloworld2.py @@ -0,0 +1,47 @@ +# coding: utf-8 +import tornado.ioloop +import tornado.gen +import time +import sys +sys.path.insert(0, "../../../protobuf/python/proto") +from datetime import datetime +from nats.io.utils import new_inbox +from nats.io import Client as NATS +import message_pb2 + +@tornado.gen.coroutine +def main(): + nc = NATS() + + # Establish connection to the server. + options = { "verbose": True, "servers": ["nats://127.0.0.1:4222"] } + yield nc.connect(**options) + + def discover(msg=None): + channel_message = message_pb2.ChannelMessage() + channel_message.ParseFromString(msg.data) + print("[Received]: %s" % channel_message) + + + send_message = message_pb2.ChannelMessage() + send_message.chan_num = 5 + #send_message.from = "python" + send_message.message = "Hello, World!" + + sid = yield nc.subscribe("world.channel_message", "", discover) + + yield nc.publish("world.channel_message", send_message.SerializeToString()) + + loop = tornado.ioloop.IOLoop.instance() + yield tornado.gen.Task(loop.add_timeout, time.time() + 20) + try: + start = datetime.now() + # Make roundtrip to the server and timeout after 1 second + yield nc.flush(1) + end = datetime.now() + print("Latency: %d µs" % (end.microsecond - start.microsecond)) + except tornado.gen.TimeoutError, e: + print("Timeout! Roundtrip too slow...") + +if __name__ == '__main__': + tornado.ioloop.IOLoop.instance().run_sync(main) \ No newline at end of file