共用方式為


適用於 JavaScript 的 Web PubSub 用戶端連結庫

Azure Web PubSub 是一項雲端服務,可協助開發人員大規模輕鬆地在 Web 應用程式中建置具有發佈-訂閱模式的即時功能。

任何需要伺服器和客戶端之間或遵循發佈訂閱模式之客戶端之間即時傳訊的案例,都可以受益於使用 Web PubSub。 開發人員不再需要以間隔傳送重複的 HTTP 要求來輪詢伺服器,這是浪費且難以調整的。

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

  • 簡化管理客戶端連線
  • 簡化在客戶端之間傳送訊息
  • 在非預期的用戶端連線卸除之後自動重試
  • 從連線中斷復原之後,可靠地以數位和順序傳遞訊息

溢出

此處所使用詞彙的詳細數據會在 重要概念 一節中說明。

此連結庫裝載於 NPM 上。


開始使用

目前支援的環境

必要條件

1. 安裝 @azure/web-pubsub-client 套件

npm install @azure/web-pubsub-client

2.與 Web PubSub 資源連線

用戶端會使用用戶端存取 URL 來連線及驗證服務,其遵循的 wss://<service_name>.webpubsub.azure.com/client/hubs/<hub_name>?access_token=<token>模式。 用戶端可以有數種方式來取得用戶端存取URL。 在此快速入門中,您可以從 Azure 入口網站複製並貼上一個,如下所示。 (針對生產環境,您的用戶端通常會在應用程式伺服器上取得用戶端存取URL。 請參閱下方的詳細 數據 )

get_client_url

如上圖所示,用戶端具有傳送訊息的許可權,並加入名為 「group1」 的特定群組。

// Imports the client libray
const { WebPubSubClient } = require("@azure/web-pubsub-client");

// Instantiates the client object
const client = new WebPubSubClient("<client-access-url>");

// Starts the client connection with your Web PubSub resource
await client.start();

// ...
// 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

// Specifies the group to join
let groupName = "group1";

// Registers a listener for the event 'group-message' early before joining a group to not miss messages
client.on("group-message", (e) => {
  console.log(`Received message: ${e.message.data}`);
});

// A client needs to join the group it wishes to receive messages from
await client.joinGroup(groupName);

4.將訊息傳送至群組

// ...continues the code snippet from above

// Send a message to a joined group
await client.sendToGroup(groupName, "hello world", "text");

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

範例

新增已連線、已中斷連線和已停止事件的回呼

  1. 當用戶端成功連線到您的 Web PubSub 資源時,就會 connected 觸發事件。
client.on("connected", (e) => {
  console.log(`Connection ${e.connectionId} is connected.`);
});
  1. 當用戶端中斷連線且無法復原連線時, disconnected 就會觸發事件。
client.on("disconnected", (e) => {
  console.log(`Connection disconnected: ${e.message}`);
});
  1. stopped用戶端中斷連線且用戶端停止嘗試重新連線時,就會觸發事件。 這通常會在呼叫 之後 client.stop() 發生,或 autoReconnect 已停用或嘗試重新連線的指定限制已達到。 如果您要重新啟動用戶端,您可以在已停止的事件中呼叫 client.start()
// Registers a listener for the "stopped" event
client.on("stopped", () => {
  console.log(`Client has stopped`);
});

使用交涉伺服器以程式設計方式產生用戶端存取URL

在生產環境中,用戶端通常會從應用程式伺服器擷取用戶端存取 URL。 伺服器會保存 Web PubSub 資源的 連接字串,並使用伺服器連結庫 @azure/web-pubsub的說明產生用戶端存取 URL。

1. 應用程式伺服器

下列代碼段是應用程式伺服器的範例,會 /negotiate 公開路徑並傳回用戶端存取URL。

// This code snippet uses the popular Express framework
const express = require('express');
const app = express();
const port = 8080;

// Imports the server library, which is different from the client library
const { WebPubSubServiceClient } = require('@azure/web-pubsub');
const hubName = 'sample_chat';

const serviceClient = new WebPubSubServiceClient("<web-pubsub-connectionstring>", hubName);

// Note that the token allows the client to join and send messages to any groups. It is specified with the "roles" option.
app.get('/negotiate', async (req, res) => {
  let token = await serviceClient.getClientAccessToken({roles: ["webpubsub.joinLeaveGroup", "webpubsub.sendToGroup"] });
  res.json({
    url: token.url
  });
});

app.listen(port, () => console.log(`Application server listening at http://localhost:${port}/negotiate`));

2. 用戶端

下列代碼段是用戶端的範例。

const { WebPubSubClient } = require("@azure/web-pubsub-client")

const client = new WebPubSubClient({
  getClientAccessUrl: async () => {
    let value = await (await fetch(`/negotiate`)).json();
    return value.url;
  }
});

await client.start();

若要查看此範例的完整程序代碼,請參閱 samples-browser


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

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

// Registers a listener for the "server-message". The callback will be invoked when your application server sends message to the connectionID, to or broadcast to all connections.
client.on("server-message", (e) => {
  console.log(`Received message ${e.message.data}`);
});

// Registers a listener for the "group-message". The callback will be invoked when the client receives a message from the groups it has joined.
client.on("group-message", (e) => {
    console.log(`Received message from ${e.message.group}: ${e.message.data}`);
});

處理重新加入失敗

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

不過,您應該留意 autoRejoinGroup其限制。

  • 用戶端只能重新加入原本由用戶端程式代碼加入的群組, 而不是 由伺服器端程式代碼加入。
  • 「重新加入群組」作業可能會因為各種原因而失敗,例如客戶端沒有加入群組的許可權。 在這種情況下,您必須新增回呼來處理此失敗。
// By default autoRejoinGroups=true. You can disable it by setting to false.
const client = new WebPubSubClient("<client-access-url>", { autoRejoinGroups: true });

// Registers a listener to handle "rejoin-group-failed" event
client.on("rejoin-group-failed", e => {
  console.log(`Rejoin group ${e.group} failed: ${e.error}`);
})

作業和重試

根據預設,、client.leaveGroup()client.sendToGroup()client.sendEvent() 之類的client.joinGroup()作業有三個重試。 您可以透過 messageRetryOptions進行設定。 如果所有重試都失敗,將會擲回錯誤。 您可以藉由傳入與先前的重試相同 ackId ,讓 Web PubSub 服務可以重複資料刪除作業,來繼續重試。

try {
  await client.joinGroup(groupName);
} catch (err) {
  let id = null;
  if (err instanceof SendMessageError) {
    id = err.ackId;
  }
  await client.joinGroup(groupName, {ackId: id});
}

指定子通訊協定

您可以變更用戶端要使用的子程式。 根據預設,用戶端會使用 json.reliable.webpubsub.azure.v1。 您可以選擇使用 json.reliable.webpubsub.azure.v1json.webpubsub.azure.v1

// Change to use json.webpubsub.azure.v1
const client = new WebPubSubClient("<client-access-url>", { protocol: WebPubSubJsonProtocol() });
// Change to use json.reliable.webpubsub.azure.v1
const client = new WebPubSubClient("<client-access-url>", { protocol: WebPubSubJsonReliableProtocol() });

重要概念

連線

連線也稱為用戶端或用戶端連線,代表連線到 Web PubSub 的個別 WebSocket 連線。 成功連線時,Web PubSub 會將唯一聯機標識碼指派給此連線。 每個都會 WebPubSubClient 建立自己的獨佔連線。

復原

如果使用可靠通訊協定的用戶端中斷連線,新的 WebSocket 會嘗試使用遺失連線的連線標識碼來建立。 如果已成功連線新的 WebSocket 連線,就會復原連線。 在用戶端中斷連線時,服務會保留用戶端的內容,以及用戶端已訂閱的所有訊息,以及客戶端復原時,服務會將這些訊息傳送至用戶端。 如果服務傳回 WebSocket 錯誤碼 1008 或復原嘗試持續超過 30 秒,復原就會失敗。

重新連接

重新聯機會在用戶端連線中斷且無法復原時發生。 重新聯機會啟動新的連線,而新的連線具有新的連線標識碼。 不同於復原,服務會將重新連線的用戶端視為新的用戶端連線。 用戶端連線需要重新加入群組。 根據預設,客戶端連結庫會在重新連線之後重新加入群組。

集線器

中樞是一組用戶端連線的邏輯概念。 通常,您會針對一個用途使用一個中樞,例如聊天中樞或通知中樞。 建立用戶端連線時,它會連線到中樞,並在其存留期間屬於該中樞。 不同的應用程式可以使用不同的中樞名稱來共用一個 Web PubSub。

分組

群組是中樞連線的子集。 您可以隨時在群組中新增用戶端連線,或從群組中移除用戶端連線。 例如,當用戶端加入聊天室時,或當用戶端離開聊天室時,便可將此聊天室視為群組。 用戶端可以加入多個群組,而群組可以包含多個用戶端。

使用者

Connections 至 Web PubSub 可以屬於一個使用者。 使用者可能會有多個連線,例如,當單一使用者跨多個裝置或多個瀏覽器索引標籤連線時。


用戶端存留期

每個 Web PubSub 用戶端都能夠安全地快取,並作為應用程式的存留期單一使用。 已註冊的事件回呼會與客戶端共用相同的存留期。 這表示您可以隨時新增或移除回呼,註冊狀態將不會在重新連線或用戶端停止之後變更。


JavaScript 套件組合

若要在瀏覽器中使用此用戶端連結庫,首先您必須使用配套程式。 如需如何執行這項操作的詳細資訊,請參閱我們的 統合檔


疑難排解

  • 啟用記錄

    使用此程式庫時,您可以設定下列環境變數來取得偵錯記錄。

export AZURE_LOG_LEVEL=verbose

如需如何啟用記錄的詳細指示,可參閱 @azure/logger 套件文件


其他資源


參與

如果您希望向此程式庫投稿,請參閱投稿指南,深入瞭解如何組建與測試程式碼。