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

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

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[0].decode()
        if response := (await async_dispatch(request)).encode():

if __name__ == "__main__":

Start the server:

$ python


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