适用于 Python 的 Azure Web PubSub 客户端库

备注

有关此处使用的术语的详细信息,请参阅主要概念一文。

客户端 SDK 旨在加快开发人员的工作流;更具体地说,即:

  • 简化客户端连接的管理
  • 简化在客户端之间发送消息
  • 在意外删除客户端连接后自动重试
  • 从连接断开恢复后,按数量和顺序可靠地传递消息

如图所示,客户端与 Web PubSub 资源建立 WebSocket 连接。

Screenshot showing clients establishing WebSocket connection with a Web PubSub resource

入门

先决条件

1. 安装 azure-messaging-webpubsubclient

pip install azure-messaging-webpubsubclient

2. 连接 Web PubSub 资源

客户端使用 wss://<service_name>.webpubsub.azure.com/client/hubs/<hub_name>?access_token=<token> 连接服务并对其进行身份验证,该过程遵循 Client Access URL 模式。 客户端可以通过几种方式获取 Client Access URL。 对于本快速入门,可以从显示的 Azure 门户复制并粘贴 URL。

Screenshot showing how to get Client Access Url on Azure portal

如图所示,客户端有权将消息发送到名为 group1 的特定组并加入其中。

from azure.messaging.webpubsubclient import WebPubSubClient

client = WebPubSubClient("<<client-access-url>>")
with client:
    # The client can join/leave groups, send/receive messages to and from those groups all in real-time
    ...

3. 加入组

客户端只能从已加入的组接收消息,在接收消息时需要添加回调以指定逻辑。

# ...continues the code snippet from above

# Registers a listener for the event 'group-message' early before joining a group to not miss messages
group_name = "group1";
client.on("group-message", lambda e: print(f"Received message: {e.data}"));

# A client needs to join the group it wishes to receive messages from
client.join_group(groupName);

4. 向组发送消息

# ...continues the code snippet from above

# Send a message to a joined group
client.send_to_group(group_name, "hello world", "text");

# In the Console tab of your developer tools found in your browser, you should see the message printed there.

示例

connecteddisconnectedstopped 事件添加回调

  1. 当客户端成功连接到 Web PubSub 资源时,将触发 connected 事件。

    client.on("connected", lambda e: print(f"Connection {e.connection_id} is connected"))
    
  2. 当客户端断开连接且无法恢复连接时,将触发 disconnected 事件。

    client.on("disconnected", lambda e: print(f"Connection disconnected: {e.message}"))
    
  3. 当客户端断开连接stopped停止尝试重新连接时,将触发 事件。 这通常发生在调用 client.stop()、禁用 auto_reconnect 或达到尝试重新连接时的指定限制之后。 如果要重启客户端,可以在已停止事件中调用 client.start()

    client.on("stopped", lambda : print("Client has stopped"))
    

客户端使用来自应用程序服务器或已加入组的消息

客户端可以添加回调以使用来自应用程序服务器或组的消息。 请注意,对于 group-message 事件,客户端只能接收已加入的组消息。

# Registers a listener for the "server-message". The callback is invoked when your application server sends message to the connectionID, to or broadcast to all connections.
client.on("server-message", lambda e: print(f"Received message {e.data}"))

# Registers a listener for the "group-message". The callback is invoked when the client receives a message from the groups it has joined.
client.on("group-message", lambda e: print(f"Received message from {e.group}: {e.data}"))

句柄重新加入失败

当客户端断开连接且无法恢复时,将在 Web PubSub 资源中清理所有组上下文。 这意味着客户端重新连接时,需要重新加入组。 默认情况下,客户端已启用 auto_rejoin_groups 选项。

但是,应注意 auto_rejoin_groups 的限制。

  • 客户端只能重新加入最初通过客户端代码而不是服务器端代码加入的组。
  • “重新加入组”操作可能会由于各种原因而失败,例如,客户端没有加入组的权限。 在这种情况下,需要添加回调来处理此问题。
# By default auto_rejoin_groups=True. You can disable it by setting to False.
client = WebPubSubClient("<client-access-url>", auto_rejoin_groups=True);

# Registers a listener to handle "rejoin-group-failed" event
client.on("rejoin-group-failed", lambda e: print(f"Rejoin group {e.group} failed: {e.error}"))

操作和重试

默认情况下,操作(如 client.join_group()client.leave_group()client.send_to_group()client.send_event())有三次重试机会。 可以通过关键字参数进行配置。 如果所有重试都失败,则会引发错误。 可以通过传入与之前的重试相同的 ack_id 来继续重试,以便 Web PubSub 服务可以删除重复操作。

try:
  client.join_group(group_name)
except SendMessageError as e:
  client.join_group(group_name, ack_id=e.ack_id)

疑难解答

启用日志

使用此库时,可设置以下环境变量来获取调试日志。

export AZURE_LOG_LEVEL=verbose

有关如何启用日志的更详细说明,请查看 @azure/logger 包文档

实时跟踪

使用来自 Azure 门户的实时跟踪工具来检查通过 Web PubSub 资源的实时消息流量。