ZeroMQ¶
Using pyzmq with a REP socket, which answers one request at a time.
Sync¶
import zmq
from jsonrpcserver import Result, Success, dispatch, method
@method
def ping() -> Result:
return Success("pong")
if __name__ == "__main__":
socket = zmq.Context().socket(zmq.REP)
# A bigger message disconnects the client. The default is no limit.
socket.setsockopt(zmq.MAXMSGSIZE, 1_000_000)
socket.bind("tcp://127.0.0.1:8000")
while True:
request = socket.recv_string()
# A REP socket must reply to every request, so a notification gets an
# empty message. max_batch_size: see the Security page.
socket.send_string(dispatch(request, max_batch_size=100))
asyncio¶
With pyzmq's zmq.asyncio:
import asyncio
import zmq
import zmq.asyncio
from jsonrpcserver import Result, Success, async_dispatch, method
@method
async def ping() -> Result:
return Success("pong")
async def main() -> None:
socket = zmq.asyncio.Context().socket(zmq.REP)
# A bigger message disconnects the client. The default is no limit.
socket.setsockopt(zmq.MAXMSGSIZE, 1_000_000)
socket.bind("tcp://127.0.0.1:8000")
while True:
request = await socket.recv_string()
# max_batch_size: see the Security page.
await socket.send_string(await async_dispatch(request, max_batch_size=100))
if __name__ == "__main__":
asyncio.run(main())
Notes¶
A REP socket must send a reply for every message it receives, before it can receive the next one. So a notification gets an empty message back, which the client should ignore.
MAXMSGSIZE makes ZeroMQ drop a client that sends a bigger message. There's
no limit by default. max_batch_size limits how many requests one batch can
hold. See Security.
The examples bind to 127.0.0.1. tcp://*:8000 would listen on every
network interface, and ZeroMQ has no authentication unless you set up one of
its security mechanisms, such as CURVE.
Try it¶
Install pyzmq (pip install pyzmq) and run one of the examples. From Python,
jsonrpcclient's
ZeroMQ example
calls this server.