34 lines
833 B
Python
34 lines
833 B
Python
|
|
import asyncio
|
|
import nats
|
|
|
|
NATS_SERVER = "nats://localhost:4222"
|
|
TOKEN = "dfji348934jdd0i24uhjd29834ijrr0345jo0r3j034n"
|
|
|
|
count = 0
|
|
|
|
async def main():
|
|
nc = await nats.connect(NATS_SERVER, token=TOKEN)
|
|
|
|
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:
|
|
await asyncio.sleep(1)
|
|
|
|
if __name__ == '__main__':
|
|
try:
|
|
asyncio.run(main())
|
|
except KeyboardInterrupt:
|
|
pass
|