跳到主要内容

服务器 API

aiosignalr.server

SignalRServer

hub 服务器。用法见服务端指南

SignalRServer(
hub: type[Hub],
*,
options: ServerOptions | None = None,
logger: logging.Logger | None = None,
)

方法与属性

成员说明
protocol_registry{"json": JSONProtocol, "messagepack": MessagePackProtocol}
lifetime用于广播/分组的 HubLifetimeManager
dispatcher绑定 hub 方法的 HubDispatcher
async serve(host, port, *, path="/hub") -> tuple[str, int]运行独立 aiohttp 服务器
create_application(*, path="/hub")构建 aiohttp 应用
asgi_app(*, path="/hub")构建供 uvicorn/FastAPI 使用的 ASGI 应用
async close()关闭独立服务器
get_connection(connection_id)查找活跃的连接上下文

ServerOptions

字段默认说明
keep_alive_interval15.0服务器心跳间隔
client_timeout_interval30.0静默客户端超时
handshake_timeout15.0握手截止时间
maximum_parallel_invocations1每连接并发调用数
maximum_receive_message_size32768最大入站帧大小
stream_buffer_capacity10上传流队列容量
long_polling_timeout15.0长轮询时长
enable_detailed_errorsFalse向客户端发送异常详情
allow_stateful_reconnectsFalse开启状态化重连
stateful_reconnect_buffer_size100_000出站缓冲字节
stateful_reconnect_timeout30.0断线连接保留的秒数

Hub

hub 基类。公共方法可被调用;异步生成器成为流式方法。

  • self.clients —— HubClients 代理(见下)。
  • self.groups —— 调用者成员关系的 GroupsManager
  • self.context —— 含 connection_idheadersqueryuser_idHubContext
  • async on_connected() —— 按连接触发的钩子。
  • async on_disconnected(exception) —— 按连接触发的钩子。

HubClients

成员说明
all_面向所有客户端的代理(send(method, *args)
others除调用者外的所有客户端
connection(id)单条连接
connections(ids)多条连接
group(name)分组内成员
groups(names)多个分组成员
user(id)带指定用户 id 的连接
users(ids)带多个用户 id 的连接
caller调用者(invoke(...) 支持客户端结果)

HubLifetimeManager / DefaultHubLifetimeManager

用于广播与分组的抽象注册表。DefaultHubLifetimeManager 是内存实现:跟踪 连接、维护分组、每条广播按协议序列化一次。子类化以接入分布式 backplane。

HubConnectionContext

每连接服务器状态(连接 id、协商好的协议、出站传输、消息缓冲、调用跟踪)。 通常只通过 hub 方法中的 self.context 或自定义 lifetime/dispatcher 代码交互。

  • has_transport —— 是否已挂载出站传输。
  • connection_id —— 逻辑连接 id。
  • use_stateful_reconnect —— ack 协议是否生效。
  • async send(message) / send_bytes(data) / send_serialized(data) —— 出站写入(走缓冲的路径)。
  • wait_closed() —— 连接关闭时解析。

IncomingStream

绑定到上传流参数(async for item in stream)的异步可迭代对象。

StreamTracker

跟踪一条连接的客户端上传流。

HubDispatcher

发现 hub 方法并路由消息。见方法解析规则

asgi_app

asgi_app(server, *, path="/hub") —— 返回普通 ASGI 应用;也可用 server.asgi_app()