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_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 ###!
  • 5
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值