適用於 Python 的 Azure Web PubSub 用戶端連結庫

備註

本文所用詞彙的詳細資料,會在《重要概念》一文說明。

用戶端 SDK 旨在加速開發人員的工作流程;更具體地來說,是要

  • 簡化管理客戶端連線
  • 簡化在客戶端之間傳送訊息
  • 在客戶端連線意外卸除之後自動重試
  • 在從連線卸除復原後,按數量和順序可靠地傳遞訊息

如下圖所示,您的用戶端會使用 Web PubSub 資源建立 WebSocket 連線。

顯示用戶端使用 Web PubSub 資源建立 WebSocket 連線的螢幕快照

入門指南

先決條件

1.安裝 azure-messaging-webpubsubclient 套件

pip install azure-messaging-webpubsubclient

2.與 Web PubSub 資源連線

用戶端會使用 Client Access URL 來連線及驗證服務,其遵循的 wss://<service_name>.webpubsub.azure.com/client/hubs/<hub_name>?access_token=<token>模式。 用戶端可以有幾種方式可取得 Client Access URL。 在本快速入門中,您可以從顯示的 Azure 入口網站複製並貼上一個。

顯示如何在 Azure 入口網站 上取得用戶端存取 URL 的螢幕快照

如上圖所示,用戶端有權限將訊息傳送至名為 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.加入群組

用戶端只能從已加入的群組接收訊息,而且您需要新增回呼,以在接收訊息時指定邏輯。

from azure.messaging.webpubsubclient.models import CallbackType

# ...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.subscribe(CallbackType.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.

範例

新增、 disconnectedstopped 事件的回connected

  1. 當用戶端成功連線到您的 Web PubSub 資源時,就會觸發 connected 事件。

    from azure.messaging.webpubsubclient.models import CallbackType
    
    client.subscribe(CallbackType.CONNECTED, lambda e: print(f"Connection {e.connection_id} is connected"))
    
  2. 當用戶端中斷連線且無法復原連線時,就會觸發 disconnected 事件。

    from azure.messaging.webpubsubclient.models import CallbackType
    
    client.subscribe(CallbackType.DISCONNECTED, lambda e: print(f"Connection disconnected: {e.message}"))
    
  3. 當用戶端中斷連線stopped用戶端停止嘗試重新連線時,就會觸發 事件。 這通常是在呼叫 client.stop() 之後發生,或 auto_reconnect 已停用或嘗試重新連線的指定限制。 如果您想要重新啟動用戶端,您可以在已停止的事件中呼叫 client.start()

    from azure.messaging.webpubsubclient.models import CallbackType
    
    client.subscribe(CallbackType.STOPPED, lambda : print("Client has stopped"))
    

用戶端會取用來自應用程式伺服器或已加入群組的訊息

用戶端可以新增回呼,以取用來自應用程式伺服器或群組的訊息。 請注意,針對 group-message 事件,用戶端 只能 接收已加入的群組訊息。

from azure.messaging.webpubsubclient.models import CallbackType

# 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.subscribe(CallbackType.CONNECTED, 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.subscribe(CallbackType.GROUP_MESSAGE, lambda e: print(f"Received message from {e.group}: {e.data}"))

處理重新加入失敗

當用戶端中斷連線且無法復原時,會在您的 Web PubSub 資源中清除所有群組內容。 這表示當用戶端重新連線時,它必須重新加入群組。 根據預設,用戶端已啟用 auto_rejoin_groups 選項。

不過,您應該注意 auto_rejoin_groups的限制。

  • 用戶端只能重新加入原本 由用戶端程式代碼所聯結的群組, 而不是 伺服器端程序代碼
  • 「重新加入群組」作業可能會因為各種原因而失敗,例如,客戶端沒有加入群組的許可權。 在這種情況下,您必須新增回呼來處理此失敗。
from azure.messaging.webpubsubclient.models import CallbackType

# 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.subscribe(CallbackType.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/記錄器套件檔。

實時追蹤

從 Azure 入口網站使用 Live Trace 工具,透過 Web PubSub 資源檢查即時訊息流量。