WebSockets异常:连接已关闭OK:code=1000(OK),无原因。

6
  • 我正在尝试从一个使用websocket的网站接收数据。它的工作原理如下图所示: websocket握手

以下是获取数据的代码:

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))

收到约100条消息后,我遇到了这个错误:
websockets.exceptions.ConnectionClosedOK: code = 1000 (OK), no reason
  • 我尝试设置超时时间请求头,但这些都没有帮助。

жҲ‘жҖҖз–‘еӣҫзүҮдёӯжҳҫзӨәзҡ„PINGж¶ҲжҒҜжҳҜеҗҰжҳҜз”ұwebsocketsжЁЎеқ—иҮӘеҠЁеҸ‘йҖҒзҡ„пјҹ - Mostafa Najmi
1个回答

5
我通过创建一个发送 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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接