PUB-SUB 패턴의 예제를 asyncio 버전으로 바꾼 예제이다.
publisher.py
import sys
import random
import asyncio
import zmq
import zmq.asyncio
ctx = zmq.asyncio.Context()
async def run_server(port=5556):
sock = ctx.socket(zmq.PUB)
sock.bind(f'tcp://*:{port}')
msg_no = 0
while True:
zip_code = random.randrange(1, 10_0000)
temp = random.randrange(- 80, 135)
hum = random.randrange(10, 60)
msg = f'{zip_code:05d} {temp:-3d} {hum:-2d} {msg_no:06d}'
await sock.send_string(msg)
msg_no = (msg_no + 1) % 100_0000
if __name__ == '__main__':
asyncio.run(run_server())
ctx.destroy()
subscribe.py
import sys
import asyncio
import zmq
import zmq.asyncio
ctx = zmq.asyncio.Context()
async def run_client(port=5556, zf='10001'):
sock = ctx.socket(zmq.SUB)
sock.connect(f'tcp://localhost:{port}')
sock.setsockopt_string(zmq.SUBSCRIBE, zf)
s = 0
for _ in range(50):
msg = await sock.recv_string()
print(f'RECEIVED: {msg}')
z, t, h, n = msg.split()
s += int(t)
print(f"AVERAGE TEMPERATURE FOR {z}: {s/50:+.2f}")
sock.close()
if __name__ == '__main__':
asyncio.run(run_client(
zf=sys.argv[1] if len(sys.argv) > 1 else '10001'))
ctx.destroy()