working version

This commit is contained in:
marys
2025-09-18 13:01:27 +02:00
parent a444dd6e4e
commit 3b6cbfa51d
2 changed files with 25 additions and 27 deletions

View File

@@ -5,33 +5,29 @@ import nats
NATS_SERVER = "nats://localhost:4222"
TOKEN = "dfji348934jdd0i24uhjd29834ijrr0345jo0r3j034n"
async def message_handler(msg):
subject = msg.subject
reply = msg.reply
data = msg.data.decode()
print(f"Received a message on '{subject} {reply}': {data}")
count = 0
async def main():
# It is very likely that the demo server will see traffic from clients other than yours.
# To avoid this, start your own locally and modify the example to use it.
nc = await nats.connect(NATS_SERVER, token=TOKEN)
# You can also use the following for TLS against the demo server.
#
# nc = await nats.connect("tls://demo.nats.io:4443")
async def message_handler(msg):
subject = msg.subject
reply = msg.reply
data = msg.data.decode()
global count
print(f"Received a message on '{subject} {reply}': {data}")
await nc.publish(reply, f"response-{count}".encode("utf-8"))
count = count + 1
# Simple publisher and async subscriber via coroutine.
await nc.subscribe("foo", cb=message_handler)
await nc.subscribe("foo2", cb=message_handler)
while True:
sub = await nc.subscribe("foo", cb=message_handler)
await asyncio.sleep(0.1)
await asyncio.sleep(1)
if __name__ == '__main__':
try:
asyncio.run(main())
except KeyboardInterrupt:
pass
pass