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

为何通过websocket获取Binance数据流的代码无响应无报错

问题现象

开发Binance交易机器人时,下述用于通过websocket客户端读取Binance数据流消息的代码运行后完全无响应,且未抛出任何错误:

import websocket


SOCKET = "wss://stream.binance.com:9443/ws/ethusdt@kline_1m"

def on_open(ws):
    print('opened connection')

def on_close(ws):
    print('closed connection')

def on_message(ws):
    print('receive message')
    
ws = websocket.WebSocketApp(SOCKET, on_open=on_open, on_close=on_close, on_message=on_message)
ws.run_forever()
故障原因

核心问题是回调函数签名不符合websocket-client库的调用规则:

  • 库触发on_message回调时,固定传入两个参数:第一个是websocket连接实例,第二个是接收到的消息内容
  • 现有代码中on_message仅定义了1个参数,回调触发时会抛出参数数量不匹配的TypeError,而该库默认会吞掉回调函数内抛出的所有异常,不会向外打印错误信息,导致程序表面看起来无响应
  • 如果运行后连opened connection的提示都看不到,大概率是本地网络无法连通Binance的websocket服务,因为没有配置错误回调,连接失败的异常被完全隐藏。
修复方法
  • 修正on_message函数签名,补充消息接收参数
  • 新增on_error回调,打印运行时异常方便后续排查问题
  • 若本地网络无法直连Binance,在run_forever()中添加本地代理配置
  • 适配新版本库的on_close回调参数要求,避免关闭连接时出现隐式报错

修复后的可运行代码:

import websocket

SOCKET = "wss://stream.binance.com:9443/ws/ethusdt@kline_1m"

def on_open(ws):
    print('opened connection')

def on_close(ws, close_status, close_msg):
    print('closed connection', close_status, close_msg)

def on_error(ws, error):
    print('connection error:', error)

def on_message(ws, message):
    print('receive message:', message)
    
ws = websocket.WebSocketApp(
    SOCKET,
    on_open=on_open,
    on_close=on_close,
    on_message=on_message,
    on_error=on_error
)
# 网络受限时替换为自己的本地代理配置即可
# ws.run_forever(proxy_type="http", http_proxy_host="127.0.0.1", http_proxy_port=7890)
ws.run_forever()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 08:15:43