当前位置:   article > 正文

python websocket 断线自动重连_websocket._exceptions.websocketconnectionclosedexc

websocket._exceptions.websocketconnectionclosedexception: connection to remo

搜索了半天,网上都是什么心跳重连,人现在的包都装好了,不知道你们咋还那么多问题,
目前的问题是,客户端由于网络等等各种原因,断开了,这种情况的重连如下:
先定义连接函数

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() 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

再定义错误函数

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!")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

设置属性全部global即可

global reconnect_count
global ws
ws=None
reconnect_count=0
  • 1
  • 2
  • 3
  • 4
<class 'websocket._exceptions.WebSocketConnectionClosedException'>
Connection is already closed.
正在尝试第4次重连
<class 'KeyboardInterrupt'>

其他error!
### closed ###!
### closed ###!
### closed ###!
### closed ###!
### closed ###!
### closed ###!
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/91461
推荐阅读
相关标签
  

闽ICP备14008679号