1006 连接关闭异常错误与 python 3.7 websockets [英] 1006 Connection closed abnormally error with python 3.7 websockets
问题描述
我遇到了与 Python websockets 的 github 问题相同的问题:https://github.com/aaugustin/websockets/issues/367
I'm having the same problem as this github issue with python websockets: https://github.com/aaugustin/websockets/issues/367
不过,提议的解决方案对我不起作用.我得到的错误是:
The proposed solution isn't working for me though. The error I'm getting is:
websockets.exceptions.ConnectionClosed: WebSocket 连接被关闭:代码 = 1006(连接异常关闭 [内部]),没有原因
websockets.exceptions.ConnectionClosed: WebSocket connection is closed: code = 1006 (connection closed abnormally [internal]), no reason
这是我的代码:
async def get_order_book(symbol):
with open('test.csv', 'a+') as csvfile:
csvw = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
DT = Data(data=data, last_OB_id=ob_id, last_TR_id=tr_id, sz=10, csvw=csvw)
while True:
if not websocket.open:
print('Reconnecting')
websocket = await websockets.connect(ws_url)
else:
resp = await websocket.recv()
update = ujson.loads(resp)
DT.update_data(update)
async def get_order_books():
r = requests.get(url='https://api.binance.com/api/v1/ticker/24hr')
await asyncio.gather(*[get_order_book(data['symbol']) for data in r.json()])
if __name__ == '__main__':
asyncio.run(get_order_books())
我一直在测试它的方法是关闭我的互联网连接,但在 10 秒延迟后它仍然返回 1006 错误.
The way I've been testing it is by closing my internet connection, but after a ten second delay it still returns the 1006 error.
我正在运行 Python 3.7 和 Websockets 7.0.
I'm running Python 3.7 and Websockets 7.0.
让我知道你的想法,谢谢!
Let me know what your thoughts are, thanks!
推荐答案
于是我找到了解决方案:
So I found the solution:
当连接关闭时,它出于某种原因跳出 while 循环.所以为了保持 websocket 运行,你必须包围
When the connection closes, it breaks out of the while loop for some reason. So in order to keep the websocket running you have to surround
resp = await websocket.recv()
with try ... except and have
with try ... except and have
print('Reconnecting')
websocket = await websockets.connect(ws_url)
在异常处理部分.
这篇关于1006 连接关闭异常错误与 python 3.7 websockets的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!