You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在请求的币安API资产无效时自动关闭对应的websocket连接

解决方案

实现逻辑

通过异步定时器实现超时自动关闭的逻辑:连接建立后启动倒计时,倒计时结束前收到消息则说明币种支持,直接取消倒计时并关闭连接;倒计时结束未收到消息则说明币种不支持,主动触发连接关闭。

完整可运行代码

import ssl
import threading
import websocket

# 资产查询超时时间,单位秒,可自行调整
ASSET_CHECK_TIMEOUT = 3

def on_open(ws):
    print('connection: successful')
    # 连接建立后启动超时定时器,超时后自动关闭连接
    ws.timeout_timer = threading.Timer(ASSET_CHECK_TIMEOUT, ws.close)
    ws.timeout_timer.start()

def on_close(ws, *args):
    print('connection: lost')
    # 关闭前取消定时器避免资源泄漏
    if hasattr(ws, 'timeout_timer'):
        ws.timeout_timer.cancel()
    print("---------------------------------------------------")

def on_message(ws, message):
    # 收到消息说明币种有效,先取消定时器
    if hasattr(ws, 'timeout_timer'):
        ws.timeout_timer.cancel()
    print(f"message received: 该资产平台支持")
    ws.close()

def on_error(ws, message):
    print(f"error: {message}")

assets = ['tribe', 'pax']
for asset in assets:
    print(f"当前查询资产: {asset}")
    SOCKET = f"wss://stream.binance.com:9443/ws/{asset}usdt@ticker"
    ws = websocket.WebSocketApp(SOCKET, 
                                on_open=on_open, 
                                on_close=on_close, 
                                on_message=on_message,
                                on_error=on_error)
    ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})

关键修改说明

  • 引入threading模块实现异步倒计时,不会阻塞websocket的消息监听
  • 超时时间可通过修改ASSET_CHECK_TIMEOUT常量自定义,根据网络情况调整即可
  • 所有回调中统一处理定时器的取消逻辑,避免出现野线程导致的资源占用
  • 测试效果:tribe会在连接建立后立刻触发消息回调,输出支持提示;pax等待3秒后自动关闭连接,无有效消息返回即为不支持。

内容的提问来源于stack exchange,提问作者Arizona

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 10:36:02