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 import method, async_dispatch as dispatch

@method
async def ping():
    return "pong"

async def main(websocket, path):
    response = await dispatch(await websocket.recv())
    if response.wanted:
        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.clients.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
pong