websockets plus json

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

Install websockets to take requests and jsonrpcserver to process them:

$ pip install websockets jsonrpcserver

Create a server.py:

import asyncio
import websockets
from jsonrpcserver.aio import methods
from jsonrpcserver.response import NotificationResponse

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

async def main(websocket, path):
    request = await websocket.recv()
    response = await methods.dispatch(request)
    if not response.is_notification:
        await websocket.send(str(response))

start_server = websockets.serve(main, 'localhost', 5000)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

Start the server:

$ python server.py

Client

Use jsonrpcclient to send requests:

$ pip install 'jsonrpcclient[websockets]'

Create a client.py:

import asyncio
import websockets
from jsonrpcclient.websockets_client import WebSocketsClient

async def main():
    async with websockets.connect('ws://localhost:5000') as ws:
        response = await WebSocketsClient(ws).request('ping')
        print(response)

asyncio.get_event_loop().run_until_complete(main())

Run the client:

$ python client.py
--> {"jsonrpc": "2.0", "method": "ping", "id": 1}
<-- {"jsonrpc": "2.0", "result": "pong", "id": 1}
pong