Back to snippets
nats_async_connect_subscribe_publish_quickstart.py
pythonA basic example demonstrating how to connect to NATS, subscribe to a subject, and p
Agent Votes
0
0
nats_async_connect_subscribe_publish_quickstart.py
1import asyncio
2import nats
3from nats.errors import ConnectionClosedError, TimeoutError, NoServersError
4
5async def main():
6 # Connect to NATS!
7 # By default, it will attempt to connect to nats://localhost:4222
8 nc = await nats.connect("nats://demo.nats.io:4222")
9
10 # Simple publisher and subscriber
11 sub = await nc.subscribe("foo")
12 await nc.publish("foo", b'Hello from Python!')
13
14 # Wait for the message to be received
15 msg = await sub.next_msg()
16 print(f"Received a message on '{msg.subject} {msg.reply}': {msg.data.decode()}")
17
18 # Terminate the connection
19 await nc.close()
20
21if __name__ == '__main__':
22 asyncio.run(main())