[Question] How to keep reading `ws.recv()`?
azat385 opened this issue · comments
Azat Sharafetdin commented
How to subscribe and keep reading ws.recv()
?
(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())
Azat Sharafetdin commented
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())