Python的WebSocket客户端,具有低级API选项
项目描述
websocket-client
websocket-client 是一个用于 Python 的 WebSocket 客户端。它提供了对 WebSocket 的低级 API 访问。websocket-client 实现了 WebSocket 协议的 hybi-13 版本。该客户端目前不支持来自 RFC 7692 的 permessage-deflate 扩展。
文档
该项目文档可在 https://websocket-client.readthedocs.io/ 找到。
贡献
请参阅 贡献指南。
安装
您可以使用 pip install websocket-client
进行安装,或使用 pip install -e .
从本地代码副本安装。此模块已在 Python 3.8+ 上进行了测试。
有一些可选依赖项可以安装以启用特定的 websocket-client 功能。
- 要安装用于代理使用的
python-socks
和用于性能提升的wsaccel
,请使用:pip install websocket-client[optional]
- 要安装
websockets
以使用本地回声服务器运行单元测试,请使用:pip install websocket-client[test]
- 要安装
Sphinx
和sphinx_rtd_theme
以构建项目文档,请使用:pip install websocket-client[docs]
虽然不是严格依赖,但 rel 在使用带有自动重连的 run_forever
时非常有用。使用 pip install rel
安装 rel。
脚注:某些 shell,如 zsh,需要您使用 \
转义 [
和 ]
字符。
使用技巧
请参阅文档的 FAQ 获取更多指南: https://websocket-client.readthedocs.io/en/latest/faq.html
此库已知问题包括缺乏 WebSocket 压缩支持(RFC 7692)和 最少线程文档/支持。
性能
有时,send
和 validate_utf8
方法可能是瓶颈。您可以使用 skip_utf8_validation
参数禁用此库中的 UTF8 验证(并获得性能提升)。如果您想获得更好的性能,请安装 wsaccel。虽然 websocket-client 不依赖于 wsaccel,但如果可用,它将使用 wsaccel。wsaccel 将 UTF8 验证的速度加倍,并在 send
过程中将有效载荷数据作为掩码时提供非常小的 10% 性能提升。Numpy 曾被建议作为性能提升的替代方案,但 问题 #687 发现它并没有帮助。
示例
更多示例可以在 示例文档 中找到。
长连接
大多数实际的 WebSocket 情况涉及更长的连接。如果 WebSocketApp 提供了
- 一个
dispatcher
参数(异步调度器如 rel 或 pyevent) - 非零的
reconnect
参数(断开连接和尝试重新连接之间的延迟)
则 WebSocketApp 的 run_forever
循环将自动尝试重新连接到已打开的 WebSocket 连接。如果网络连接丢失
import websocket
import _thread
import time
import rel
def on_message(ws, message):
print(message)
def on_error(ws, error):
print(error)
def on_close(ws, close_status_code, close_msg):
print("### closed ###")
def on_open(ws):
print("Opened connection")
if __name__ == "__main__":
websocket.enableTrace(True)
ws = websocket.WebSocketApp("wss://api.gemini.com/v1/marketdata/BTCUSD",
on_open=on_open,
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.run_forever(dispatcher=rel, reconnect=5) # Set dispatcher to automatic reconnection, 5 second reconnect delay if connection closed unexpectedly
rel.signal(2, rel.abort) # Keyboard Interrupt
rel.dispatch()
run_forever
提供了各种基于事件的连接控制,使用回调如 on_message
和 on_error
。如果服务器优雅地关闭 WebSocket(返回 标准的 WebSocket 关闭代码),则 run_forever
不会自动重新连接。这是决定背后的逻辑。当服务器关闭 WebSocket 时,应处理自定义行为的 on_close
回调。此示例使用 rel 作为调度器以提供自动重新连接。
这是如果您想发送一条简短消息并在完成后立即断开连接的情况。例如,如果您想确认WebSocket服务器正在运行并且能够正确响应特定请求。
from websocket import create_connection
ws = create_connection("ws://echo.websocket.events/")
print(ws.recv())
print("Sending 'Hello, World'...")
ws.send("Hello, World")
print("Sent")
print("Receiving...")
result = ws.recv()
print("Received '%s'" % result)
ws.close()
项目详情
下载文件
下载适合您平台的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。
源分布
构建分布
websocket_client-1.8.0.tar.gz的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 3239df9f44da632f96012472805d40a23281a991027ce11d2f45a6f24ac4c3da |
|
MD5 | 9cffbda9eefb0a17e9c4cda3b7884493 |
|
BLAKE2b-256 | e630fba0d96b4b5fbf5948ed3f4681f7da2f9f64512e1d303f94b4cc174c24a5 |