跳到主要内容

快速开始:客户端

本教程把 Python 客户端连接到 SignalR hub、调用服务器方法,并响应服务器主动推送的消息。

1. 创建连接

import asyncio

from aiosignalr.client import HubConnection


async def main() -> None:
connection = HubConnection()
await connection.start("http://127.0.0.1:8080/hub")

# ... 使用连接 ...

await connection.stop()


asyncio.run(main())

start() 会先完成 POST /negotiate 协商,选择最优传输并完成协议握手后才返回。 默认客户端按服务器声明顺序尝试传输(WebSocket → SSE → Long Polling)。

2. 调用服务器方法

invoke() 调用方法并等待结果:

result = await connection.invoke("Add", 40, 2)
print("Add(40, 2) =", result) # 42

send() 做即发即弃的调用(不期待结果):

await connection.send("Notify", "hello")

3. 流式结果

服务器返回异步迭代器的方法可以用 stream() 消费:

async for item in await connection.stream("Counter", 3):
print("stream item:", item)

4. 接收服务器消息

on() 注册处理器。服务器调用某个方法时,所有匹配的处理器都会带上参数运行:

connection.on("message", lambda text: print("got:", text))

# 也支持异步处理器。
async def on_joined(user: str) -> None:
print(f"{user} joined the room")

connection.on("userJoined", on_joined)

如果处理器返回非 None 值,它会被作为调用结果发回服务器(即客户端结果)。

5. 完整示例

import asyncio

from aiosignalr.client import HubConnection


async def main() -> None:
connection = HubConnection()
connection.on("message", lambda text: print("got:", text))

await connection.start("ws://127.0.0.1:8080/hub")

result = await connection.invoke("Add", 40, 2)
print("Add(40, 2) =", result)

async for item in await connection.stream("Counter", 3):
print("stream item:", item)

await connection.send("Notify", "hello")
await connection.stop()


asyncio.run(main())

下一步