zeromq plus json

We’ll use ZeroMQ to take JSON-RPC requests. It should respond to “ping” with “pong”.

Install pyzmq to take requests and jsonrpcserver to process them:

$ pip install pyzmq jsonrpcserver

Create a server.py:

import zmq
from jsonrpcserver import method, dispatch

socket = zmq.Context().socket(zmq.REP)

@method
def ping():
    return "pong"

if __name__ == "__main__":
    socket.bind("tcp://*:5000")
    while True:
        request = socket.recv().decode()
        response = dispatch(request)
        socket.send_string(str(response))

Start the server:

$ python ./server.py

Client

Use jsonrpcclient to send requests:

$ pip install "jsonrpcclient[pyzmq]"
$ python
>>> from jsonrpcclient.clients.zeromq_client import ZeroMQClient
>>> ZeroMQClient('tcp://localhost:5000').request('ping').data.result
'pong'

You can also do this asynchronously with Python 3.5+.