Skip to main content

具有低级 API 选项的 Python 的 WebSocket 客户端

项目描述

文档 构建状态 编解码器 PyPI 下载 PyPI 版本

websocket客户端

websocket-client 是 Python 的 WebSocket 客户端。它提供对 WebSocket 的低级 API 的访问。websocket-client 实现 了 WebSocket 协议的hybi-13版本。此客户端当前不支持 RFC 7692中的 permessage-deflate 扩展。

文档

该项目的文档可以在 https://websocket-client.readthedocs.io/找到

贡献

请参阅贡献指南

安装

您可以使用python3 setup.py installpip3 install websocket-client 安装。该模块在 Python 3.7+ 上进行了测试。

可以安装几个可选的依赖项来启用特定的 websocket-client 功能。

  • 要安装python-socks用于代理使用和wsaccel较小的性能提升,请使用: pip3 install websocket-client[optional]
  • 要安装websockets以使用本地回显服务器运行单元测试,请使用: pip3 install websocket-client[test]
  • 要安装Sphinxsphinx_rtd_theme构建项目文档,请使用: pip3 install websocket-client[docs]

虽然不是严格的依赖关系,但relrun_forever在与自动重新连接一起 使用时很有用。安装 rel 与pip3 install rel.

脚注:某些 shell,例如 zsh,要求您使用 . 转义[and]字符\

使用技巧

查看文档的常见问题解答以获取更多指南: https ://websocket-client.readthedocs.io/en/latest/faq.html

该库的已知问题包括缺乏 WebSocket 压缩支持 (RFC 7692) 和最少的线程文档/支持

表现

和方法有时可能是瓶颈sendvalidate_utf8您可以使用参数禁用此库中的 UTF8 验证(并获得性能增强)skip_utf8_validation。如果您想获得更好的性能,请安装 wsaccel。虽然 websocket-client 不依赖于 wsaccel,但如果可用,它将被使用。wsaccel 将 UTF8 验证的速度提高一倍,并在将有效负载数据作为send流程的一部分进行屏蔽时提供非常小的 10% 的性能提升。Numpy 曾经是建议的性能增强替代方案,但 issue #687 发现它没有帮助。

例子

在示例文档中可以找到更多示例 。

长期连接

大多数现实世界的 WebSockets 情况都涉及寿命更长的连接。如果提供了调度程序参数, WebSocketApprun_forever循环将在网络连接丢失时自动尝试重新连接到打开的 WebSocket 连接,并提供各种基于事件的连接控件。 run_forever如果服务器关闭 WebSocket,则不会自动重新连接。服务器关闭 WebSocket 时的自定义行为应在on_close回调中处理。此示例使用rel 为调度程序提供自动重新连接。

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)  # Set dispatcher to automatic reconnection
    rel.signal(2, rel.abort)  # Keyboard Interrupt
    rel.dispatch()

短暂的连接

这是如果您想传达一条短消息并在完成后立即断开连接。例如,如果您想确认 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()

发布历史 发布通知| RSS订阅