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 methods
from jsonrpcserver.response import NotificationResponse

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

@methods.add
def ping():
    return 'pong'

if __name__ == '__main__':
    socket.bind('tcp://*:5000')
    while True:
        request = socket.recv().decode()
        response = methods.dispatch(request)
        if not isinstance(response, NotificationResponse):
            socket.send_string(str(response))

Start the server:

$ python ./server.py

Client

Use jsonrpcclient to send requests:

$ pip install 'jsonrpcclient[pyzmq]'
$ python
>>> from jsonrpcclient.zeromq_client import ZeroMQClient
>>> ZeroMQClient('tcp://localhost:5000').request('ping')
--> {"jsonrpc": "2.0", "method": "ping", "id": 1}
<-- {"jsonrpc": "2.0", "result": "pong", "id": 1}
'pong'

You can also do this asynchronously with Python 3.5+.