检查代码中是否正确设置了WebSocket连接的 Ping/Pong 操作,建议添加心跳检测,避免连接意外断开。以下是示例代码:
import websocket
import json
import threading
import time
# 设置WebSocket连接
ws = websocket.WebSocketApp('wss://stream.binance.com:9443/ws/btcusdt@aggTrade')
# 添加心跳检测
def heartbeat():
while True:
time.sleep(30)
try:
ws.ping()
except Exception as e:
print('ping failed:', e)
# 启动心跳检测线程
t = threading.Thread(target=heartbeat)
t.daemon = True
t.start()
# WebSocket连接回调函数
def on_message(ws, message):
data = json.loads(message)
print(data)
ws.on_message = on_message
# 启动WebSocket连接
ws.run_forever()