处理服务器调用
服务器可以两种方式调用客户端方法:即发即弃的通知与客户端结果 (服务器调用客户端方法并等待返回值)。
注册处理器
connection.on("target", handler)
服务器为 target 发送 Invocation(或 StreamInvocation)时,
每个已注册处理器都会带上消息参数运行:
connection.on("message", lambda text: print("got:", text))
处理器可以是异步的:
async def on_file(path: str, size: int) -> None:
await save_file(path, size)
connection.on("fileReady", on_file)
对于即发即弃的服务器调用(invocation_id is None),所有处理器都会运行,
返回值被忽略。
客户端结果
当服务器发送带调用 id 的调用(客户端结果)时,处理器的返回值会作为结果回发:
async def client_method(text: str) -> str:
return f"ack:{text}"
connection.on("client_method", client_method)
- 恰好一个处理器返回非
None值时,该值作为结果发 送。 - 没有处理器返回值时,发送空
Completion。 - 处理器抛异常时,客户端发送带错误信息的
Completion。
服务器端用 clients.caller.invoke("client_method", ...) 触发此流程
(见客户端结果)。
移除处理器
connection.remove("message", handler)
未知方法
服务器调用没有注册处理器且带调用 id 的方法时,客户端回复携带
"Unknown hub method '<target>'" 的 Completion,在服务器端表现为 HubException。
顺序
处理器按注册顺序调用。即发即弃的通知以后台任务分发,慢处理器不会阻塞帧处理。