赞
踩
搜索了半天,网上都是什么心跳重连,人现在的包都装好了,不知道你们咋还那么多问题,
目前的问题是,客户端由于网络等等各种原因,断开了,这种情况的重连如下:
先定义连接函数
def connection_tmp(ws):
websocket.enableTrace(True)
ws = websocket.WebSocketApp("ws://localhost:8000/ws",
on_message = on_message,
# on_data=on_data_test,
on_error = on_error,
on_close = on_close)
ws.on_open = on_open
try:
ws.run_forever()
except KeyboardInterrupt:
ws.close()
except:
ws.close()
再定义错误函数
def on_error(ws, error):
global reconnect_count
print(type(error))
print(error)
if type(error)==ConnectionRefusedError or type(error)==websocket._exceptions.WebSocketConnectionClosedException:
print("正在尝试第%d次重连"%reconnect_count)
reconnect_count+=1
if reconnect_count<100:
connection_tmp(ws)
else:
print("其他error!")
设置属性全部global即可
global reconnect_count
global ws
ws=None
reconnect_count=0
<class 'websocket._exceptions.WebSocketConnectionClosedException'>
Connection is already closed.
正在尝试第4次重连
<class 'KeyboardInterrupt'>
其他error!
### closed ###!
### closed ###!
### closed ###!
### closed ###!
### closed ###!
### closed ###!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。