【问题标题】:web-socket client will not connect to an APIweb-socket 客户端不会连接到 API
【发布时间】:2021-11-14 04:36:21
【问题描述】:

在网上搜索了几个小时并在 Reddit 上提出同样的问题但没有成功后,我决定注册 Stack Overflow 并在这里提出问题。

我目前正在学习有关 API 的更多教程。该特定教程正在使用 Binance API 尝试每分钟收集一次有关 BTC 价格的数据(以美元计)。为此,我导入了 WebSocket-client 以保持稳定的连接并每分钟收集一次新数据点,但是每当我运行我的代码时,什么都没有发生。控制台打印“Process finished with exit code 0”,而不是实际连接到服务器并收集数据。

这是我的代码:

import websocket

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

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

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

def on_message(ws, message):
    print('message')

ws = websocket.WebSocketApp(SOCKET, on_open=on_open, on_close=on_close, on_message=on_message)
ws.run_forever()

起初,我以为我安装了错误的 WebSocket 库(而不是我以为我使用的 WebSocket-client。常规的 WebSocket 库)但是,我没有。然后我想可能是 PyCharm 有问题,所以我在 Visual Studio Code、Sublime Text、Terminal 和 Jupyter notebook 中运行了代码,但它们都没有工作。

我的代码有什么问题吗?我尝试了无数次编辑,但到目前为止都没有奏效。

币安 API 文档:https://github.com/binance/binance-spot-api-docs/blob/master/web-socket-streams.md

我正在关注的教程:https://youtu.be/GdlFhF6gjKo?t=1112(去 18:32 左右查看他的代码)。

ps。我是一名新程序员,刚刚完成我的第一个项目(a* 寻路算法),所以不要太苛刻:)。

【问题讨论】:

  • 如果您添加 on_error 回调,我怀疑您会看到:- [SSL: CERTIFICATE_VERIFY_FAILED] 证书验证失败:无法获取本地颁发者证书
  • 这是真的。下面的答案概述了如何解决这个问题,但我仍然不太明白什么是 ssl 证书或它为什么重要......

标签: python websocket cryptocurrency


【解决方案1】:

假设这是普遍存在的 SSL 错误,然后执行以下操作:-

import websocket
import ssl

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


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

def on_close(ws, *args):
    print('connection: lost')

def on_message(ws, message):
    print('message')

def on_error(ws, message):
    print(message)

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})

【讨论】:

  • 这成功了!太感谢了。你介意解释一下什么是 SSL 错误,以及 ssl 库是如何解决这个问题的吗? - 谢谢:)
  • 感谢您的笑声,以及您提供的解决方案。我现在要谷歌了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-04
相关资源
最近更新 更多