websockets.exceptions.ConnectionClosedOK: code = 1000 (OK), 没有原因

websockets.exceptions.ConnectionClosedOK: code = 1000 (OK), no reason

这里是抓取数据的代码:

async def hello(symb_id: int):
    async with websockets.connect("wss://ws.bitpin.ir/", extra_headers = request_header, timeout=15) as websocket:
        await websocket.send('{"method":"sub_to_price_info"}')
        recv_msg = await websocket.recv()
        if recv_msg == '{"message": "sub to price info"}':
            await websocket.send(json.dumps({"method":"sub_to_market","id":symb_id}))
            recv_msg = await websocket.recv()
            counter = 1 

            while(1):
                msg = await websocket.recv()
                print(counter, msg[:100], end='\n\n')
                counter+=1

asyncio.run(hello(1))
websockets.exceptions.ConnectionClosedOK: code = 1000 (OK), no reason

我通过创建发送 PING.

的任务解决了这个错误
async def hello(symb_id: int):
    async with websockets.connect("wss://ws.bitpin.ir/", extra_headers = request_header, timeout=10, ping_interval=None) as websocket:
        await websocket.send('{"method":"sub_to_price_info"}')
        recv_msg = await websocket.recv()
        if recv_msg == '{"message": "sub to price info"}':
            await websocket.send(json.dumps({"method":"sub_to_market","id":symb_id}))
            recv_msg = await websocket.recv()
            counter = 1 

            task = asyncio.create_task(ping(websocket))
            while True:
                msg = await websocket.recv()
                await return_func(msg)
                print(counter, msg[:100], end='\n\n')
                counter+=1


async def ping(websocket):
    while True:
        await websocket.send('{"message":"PING"}')
        print('------ ping')
        await asyncio.sleep(5)