Skip to content

Instantly share code, notes, and snippets.

@sooop
Created May 31, 2019 05:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sooop/4ead47e11cb5c2659f8182718fac478f to your computer and use it in GitHub Desktop.
Save sooop/4ead47e11cb5c2659f8182718fac478f to your computer and use it in GitHub Desktop.
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()
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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment