当前位置:   article > 正文

python websocket客户端

python websocket客户端

本程序具有websocket的基本功能,其中另外加了心跳,心跳失败重连

pip install websocket-client

  1. import websocket
  2. import threading
  3. import time
  4. class WebSocketClient:
  5.     def __init__(self, url, heartbeat_interval=5):
  6.         self.url = url
  7.         self.heartbeat_interval = heartbeat_interval
  8.         self.ws = None
  9.         self.is_connected = False
  10.         self.is_heartbeat_failed = False
  11.         self.heartbeat_thread = None
  12.     def on_open(self, ws):
  13.         print("Connected to WebSocket server")
  14.         self.is_connected = True
  15.         self.is_heartbeat_failed = False
  16.         # Start the heartbeat thread
  17.         self.heartbeat_thread = threading.Thread(target=self.send_heartbeat)
  18.         self.heartbeat_thread.start()
  19.     def on_message(self, ws, message):
  20.         print(f"Received message: {message}")
  21.         # Reset heartbeat failure flag upon receiving any message
  22.         self.is_heartbeat_failed = False
  23.     def on_close(self, ws, close_status_code, close_msg):
  24.         print(f"Connection closed unexpectedly: {close_status_code}, {close_msg}")
  25.         self.is_connected = False
  26.         self.is_heartbeat_failed = True
  27.     def on_error(self, ws, error):
  28.         print(f"Error: {error}")
  29.         self.is_heartbeat_failed = True
  30.     def send_heartbeat(self):
  31.         while self.is_connected:
  32.             try:
  33.                 # Send heartbeat message
  34.                 self.ws.send("ping")
  35.                 print("Sent heartbeat: ping")
  36.                 # Wait for the next heartbeat interval
  37.                 time.sleep(self.heartbeat_interval)
  38.                 # Check if heartbeat failed
  39.                 if self.is_heartbeat_failed:
  40.                     print("Heartbeat failed, attempting to reconnect...")
  41.                     self.ws.close()
  42.                     break
  43.             except Exception as e:
  44.                 print(f"Heartbeat error: {e}")
  45.                 self.is_heartbeat_failed = True
  46.     def connect(self):
  47.         while not self.is_connected:
  48.             try:
  49.                 # Connect to WebSocket server
  50.                 self.ws = websocket.WebSocketApp(self.url,
  51.                                                  on_open=self.on_open,
  52.                                                  on_message=self.on_message,
  53.                                                  on_close=self.on_close,
  54.                                                  on_error=self.on_error)
  55.                 self.ws.run_forever()
  56.             except Exception as e:
  57.                 print(f"Connection error: {e}")
  58.             # If the connection is closed or heartbeat failed, wait before reconnecting
  59.             if not self.is_connected or self.is_heartbeat_failed:
  60.                 time.sleep(5)
  61. if __name__ == "__main__":
  62.     # Replace with your WebSocket server address
  63.     ws_url = "wss://example.com/socket"
  64.     client = WebSocketClient(ws_url)
  65.     client.connect()

在本例中,WebSocketClient类被修改为包含一个标志(is_heartbeat_failed),如果心跳失败,该标志将被设置为True。send_heartbeat方法在发送一个心跳消息后检查这个标志。如果设置了该标志,则表示心跳失败,客户端将尝试重新连接。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/85403
推荐阅读
相关标签
  

闽ICP备14008679号