赞
踩
本程序具有websocket的基本功能,其中另外加了心跳,心跳失败重连
pip install websocket-client
- import websocket
- import threading
- import time
-
- class WebSocketClient:
- def __init__(self, url, heartbeat_interval=5):
- self.url = url
- self.heartbeat_interval = heartbeat_interval
- self.ws = None
- self.is_connected = False
- self.is_heartbeat_failed = False
- self.heartbeat_thread = None
-
- def on_open(self, ws):
- print("Connected to WebSocket server")
- self.is_connected = True
- self.is_heartbeat_failed = False
-
- # Start the heartbeat thread
- self.heartbeat_thread = threading.Thread(target=self.send_heartbeat)
- self.heartbeat_thread.start()
-
- def on_message(self, ws, message):
- print(f"Received message: {message}")
-
- # Reset heartbeat failure flag upon receiving any message
- self.is_heartbeat_failed = False
-
- def on_close(self, ws, close_status_code, close_msg):
- print(f"Connection closed unexpectedly: {close_status_code}, {close_msg}")
- self.is_connected = False
- self.is_heartbeat_failed = True
-
- def on_error(self, ws, error):
- print(f"Error: {error}")
- self.is_heartbeat_failed = True
-
- def send_heartbeat(self):
- while self.is_connected:
- try:
- # Send heartbeat message
- self.ws.send("ping")
- print("Sent heartbeat: ping")
-
- # Wait for the next heartbeat interval
- time.sleep(self.heartbeat_interval)
-
- # Check if heartbeat failed
- if self.is_heartbeat_failed:
- print("Heartbeat failed, attempting to reconnect...")
- self.ws.close()
- break
-
- except Exception as e:
- print(f"Heartbeat error: {e}")
- self.is_heartbeat_failed = True
-
- def connect(self):
- while not self.is_connected:
- try:
- # Connect to WebSocket server
- self.ws = websocket.WebSocketApp(self.url,
- on_open=self.on_open,
- on_message=self.on_message,
- on_close=self.on_close,
- on_error=self.on_error)
-
- self.ws.run_forever()
-
- except Exception as e:
- print(f"Connection error: {e}")
-
- # If the connection is closed or heartbeat failed, wait before reconnecting
- if not self.is_connected or self.is_heartbeat_failed:
- time.sleep(5)
-
- if __name__ == "__main__":
- # Replace with your WebSocket server address
- ws_url = "wss://example.com/socket"
-
- client = WebSocketClient(ws_url)
- client.connect()
在本例中,WebSocketClient类被修改为包含一个标志(is_heartbeat_failed),如果心跳失败,该标志将被设置为True。send_heartbeat方法在发送一个心跳消息后检查这个标志。如果设置了该标志,则表示心跳失败,客户端将尝试重新连接。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。