subscribe_w_reply.py 805 B

12345678910111213141516171819202122232425262728293031323334353637
  1. import asyncio
  2. from nats.aio.client import Client as NATS
  3. from nats.aio.utils import new_inbox
  4. from datetime import datetime
  5. async def example():
  6. # [begin subscribe_w_reply]
  7. nc = NATS()
  8. await nc.connect(servers=["nats://demo.nats.io:4222"])
  9. future = asyncio.Future()
  10. async def cb(msg):
  11. nonlocal future
  12. future.set_result(msg)
  13. await nc.subscribe("time", cb=cb)
  14. await nc.publish_request("time", new_inbox(), b'What is the time?')
  15. await nc.flush()
  16. # Read the message
  17. msg = await asyncio.wait_for(future, 1)
  18. # Send the time
  19. time_as_bytes = "{}".format(datetime.now()).encode()
  20. await nc.publish(msg.reply, time_as_bytes)
  21. # [end subscribe_w_reply]
  22. await nc.close()
  23. loop = asyncio.get_event_loop()
  24. loop.run_until_complete(example())
  25. loop.close()