100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > python websocket 断线自动重连

python websocket 断线自动重连

时间:2019-06-16 09:15:26

相关推荐

python websocket 断线自动重连

搜索了半天,网上都是什么心跳重连,人现在的包都装好了,不知道你们咋还那么多问题,

目前的问题是,客户端由于网络等等各种原因,断开了,这种情况的重连如下:

先定义连接函数

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_opentry:ws.run_forever()except KeyboardInterrupt:ws.close() except:ws.close()

再定义错误函数

def on_error(ws, error):global reconnect_countprint(type(error))print(error)if type(error)==ConnectionRefusedError or type(error)==websocket._exceptions.WebSocketConnectionClosedException:print("正在尝试第%d次重连"%reconnect_count)reconnect_count+=1if reconnect_count<100:connection_tmp(ws)else:print("其他error!")

设置属性全部global即可

global reconnect_countglobal wsws=Nonereconnect_count=0

<class 'websocket._exceptions.WebSocketConnectionClosedException'>Connection is already closed.正在尝试第4次重连<class 'KeyboardInterrupt'>其他error!### closed ###!### closed ###!### closed ###!### closed ###!### closed ###!### closed ###!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。