explodinglabs / jsonrpcclient

Generate JSON-RPC requests and parse responses in Python

Home Page:https://www.jsonrpcclient.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Question] How to keep reading `ws.recv()`?

azat385 opened this issue · comments

How to subscribe and keep reading ws.recv()?
image
(the order on picture is from bottom to top)

import asyncio
import logging

from jsonrpcclient import Ok, parse_json, request_json
import websockets


async def main():
    async with websockets.connect("ws://localhost:5000") as ws:
        await ws.send(request_json("subscribe"))
        response = parse_json(await ws.recv())

    if isinstance(response, Ok):
        print(response.result)
    else:
        logging.error(response.message)


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

i get just one response
image

import asyncio
import websockets
from jsonrpcclient import Ok, parse_json, request_json, request


async def work():
    uri = "ws://127.0.0.1:5000"
    async with websockets.connect(uri, ping_timeout=None) as websocket:
        sub = '{"jsonrpc": "2.0", "id": 1, "method": "subscribe", "params": [....]}'
        await websocket.send(sub)
        print(f">>> {sub}")

        async def ping():
            req = "PING"
            while True:
                await websocket.send(req)
                print(f">>> {req}")
                await asyncio.sleep(5)

        async def recv():
            while True:
                resp = await websocket.recv()
                print(f"<<< {resp}")

        await asyncio.gather(ping(), recv())



if __name__ == "__main__":
    asyncio.run(work())