request_reply.py 677 B

12345678910111213141516171819202122232425262728293031
  1. import asyncio
  2. import json
  3. from nats.aio.client import Client as NATS
  4. from nats.aio.utils import new_inbox
  5. async def example():
  6. # [begin request_reply]
  7. nc = NATS()
  8. async def sub(msg):
  9. await nc.publish(msg.reply, b'response')
  10. await nc.connect(servers=["nats://demo.nats.io:4222"])
  11. await nc.subscribe("time", cb=sub)
  12. # Send the request
  13. try:
  14. msg = await nc.request("time", b'', timeout=1)
  15. # Use the response
  16. print("Reply:", msg)
  17. except asyncio.TimeoutError:
  18. print("Timed out waiting for response")
  19. # [end request_reply]
  20. await nc.close()
  21. loop = asyncio.get_event_loop()
  22. loop.run_until_complete(example())
  23. loop.close()