How to use JSON-RPC with ZeroMQ in Python - asynchronously?

zeromq json

We’ll use ZeroMQ to take JSON-RPC requests, and process them asynchronously. The server should respond to “ping” with “pong”.

Install aiozmq to take requests and jsonrpcserver to process them:

pip install aiozmq jsonrpcserver

Create a server.py:

from jsonrpcserver import method, Result, Success, async_dispatch
import aiozmq
import asyncio
import zmq


@method
async def ping() -> Result:
    return Success("pong")


async def main():
    rep = await aiozmq.create_zmq_stream(zmq.REP, bind="tcp://*:5000")
    while True:
        request = (await rep.read())[0].decode()
        if response := (await async_dispatch(request)).encode():
            rep.write((response,))


if __name__ == "__main__":
    asyncio.set_event_loop_policy(aiozmq.ZmqEventLoopPolicy())
    asyncio.get_event_loop().run_until_complete(main())

Start the server:

$ python server.py

Client

Use jsonrpcclient to send requests:

pip install pyzmq jsonrpcclient
>>> from jsonrpcclient import request_json, parse_json, Ok
>>> import zmq
>>> socket = zmq.Context().socket(zmq.REQ)
>>> socket.connect("tcp://localhost:5000")
>>> socket.send_string(request_json("ping"))
>>> response = parse_json(socket.recv().decode())
>>> response.result
'pong'