asyncins / aiowebsocket

Async WebSocket Client. Advantage: Flexible Lighter and Faster
321 stars 55 forks source link

await converse.receive() 抛出Task exception was never retrieved #18

Open David-Guo opened 2 years ago

David-Guo commented 2 years ago
async def startup(uri):
    async with AioWebSocket(uri=uri) as aws:
        converse = aws.manipulator
        jsonTxt = {
            'id': 1,
            'jsonrpc': '2.0',
            'method': "subscribe",
            'params': {
                'channel': "pools"
            }
        }
        msg = json.dumps(jsonTxt)
        await converse.send(msg)

        while True:
            receive = await converse.receive()
            print(receive.decode())
            continue

if __name__ == '__main__':
    tasks = [
        startup("ws://host:8080/a"),
        startup("ws://host:8080/b"),
        startup("ws://host:8080/c")
    ]

    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.wait(tasks))

我的代码逻辑大概如上,目的是建立多个websocket连接。但是有一个连接在接受到第一次数据之后,服务器在很长一段时间内都无法吐回数据,然后就出现了如下的异常,异常的原因是服务器太长时间没有回吐数据了

PS D:\my_code\my_crpyto_tool\LPMoniter> python .\wsGet.py
{"jsonrpc":"2.0","result":{"status":"ok","data":"ready"},"id":1}
Task exception was never retrieved
future: <Task finished coro=<startup() done, defined at .\wsGet.py:29> exception=IncompleteReadError('0 bytes read on a total of 2 expected bytes')>
Traceback (most recent call last):
  File ".\wsGet.py", line 58, in startup
    receive = await converse.receive()
  File "D:\Program\Anaconda3\lib\site-packages\aiowebsocket\converses.py", line 103, in receive
    single_message = await self.frame.read(text, mask)
  File "D:\Program\Anaconda3\lib\site-packages\aiowebsocket\freams.py", line 238, in read
    fin, code, rsv1, rsv2, rsv3, message = await self.unpack_frame(mask, maxsize)
  File "D:\Program\Anaconda3\lib\site-packages\aiowebsocket\freams.py", line 209, in unpack_frame
    frame_header = await reader(2)
  File "D:\Program\Anaconda3\lib\asyncio\streams.py", line 677, in readexactly
    raise IncompleteReadError(incomplete, n)
asyncio.streams.IncompleteReadError: 0 bytes read on a total of 2 expected bytes

服务的逻辑是,如果客户端发送 "ping“ 能主动回应 "pong”,我有试过在捕获异常然后调用 await converse.send(ping) 从而在下一次while 循环的时候拿到“pong”结果,从而保持连接,但是这个时候websocket连接已经断开了,这里能不能再出现异常之后继续保持连接呢?

while True:
    try:
        receive = await converse.receive()
    except Exception as e:
        print(e)
        await converse.send("ping")
        continue