connect_tls_url.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # [begin connect_tls_url]
  2. import asyncio
  3. import ssl
  4. import certifi
  5. from nats.aio.client import Client as NATS
  6. from nats.aio.errors import ErrTimeout
  7. async def run(loop):
  8. nc = NATS()
  9. # If using Python 3.7 in OS X and getting SSL errors, run first:
  10. #
  11. # /Applications/Python\ 3.7/Install\ Certificates.command
  12. #
  13. # Setting the tls as the scheme will use same defaults as `ssl.create_default_context()`
  14. #
  15. await nc.connect("tls://demo.nats.io:4443", loop=loop)
  16. async def message_handler(msg):
  17. subject = msg.subject
  18. reply = msg.reply
  19. data = msg.data.decode()
  20. print("Received a message on '{subject} {reply}': {data}".format(
  21. subject=subject, reply=reply, data=data))
  22. # Simple publisher and async subscriber via coroutine.
  23. sid = await nc.subscribe("foo", cb=message_handler)
  24. await nc.flush()
  25. # Stop receiving after 2 messages.
  26. await nc.auto_unsubscribe(sid, 2)
  27. await nc.publish("foo", b'Hello')
  28. await nc.publish("foo", b'World')
  29. await nc.publish("foo", b'!!!!!')
  30. await asyncio.sleep(1, loop=loop)
  31. await nc.close()
  32. # [end connect_tls_url]
  33. if __name__ == '__main__':
  34. loop = asyncio.get_event_loop()
  35. loop.run_until_complete(run(loop))
  36. loop.close()