# zmq rpc example. import curio_zmq as zmq async def rpc_server(address): ctx = zmq.Context() sock = ctx.socket(zmq.REP) sock.bind(address) while True: func, args, kwargs = await sock.recv_pyobj() try: result = func(*args, **kwargs) await sock.send_pyobj(result) except Exception as e: await sock.send_pyobj(e) if __name__ == '__main__': zmq.run(rpc_server, 'tcp://*:9000')
# zmq push example. Run the zmq_puller.py program for the client import curio_zmq as zmq async def pusher(address): ctx = zmq.Context() sock = ctx.socket(zmq.PUSH) sock.bind(address) for n in range(100): await sock.send(b'Message %d' % n) await sock.send(b'exit') if __name__ == '__main__': zmq.run(pusher, 'tcp://*:9000')
# zmq RPC client example. Requires zmq_rpcserv.py to be runnig import curio_zmq as zmq from curio import sleep, spawn from hello import fib async def ticker(): n = 0 while True: await sleep(1) print('Tick:', n) n += 1 async def client(address): # Run a background task to make sure the message passing operations don't block await spawn(ticker, daemon=True) # Compute the first 40 fibonacci numbers ctx = zmq.Context() sock = ctx.socket(zmq.REQ) sock.connect(address) for n in range(1, 40): await sock.send_pyobj((fib, (n,), {})) result = await sock.recv_pyobj() print(n, result) if __name__ == '__main__': zmq.run(client, 'tcp://localhost:9000')
# zmq pull client example. Requires zmq_pusher.py to be running import curio_zmq as zmq async def puller(address): ctx = zmq.Context() sock = ctx.socket(zmq.PULL) sock.connect(address) while True: msg = await sock.recv() if msg == b'exit': break print('Got:', msg) if __name__ == '__main__': zmq.run(puller, 'tcp://localhost:9000')