適用於 JavaScript 的 Azure Web PubSub 服務用戶端庫 - 版本 1.2.0

Azure Web PubSub 服務 是一項 Azure 受控服務,可協助開發人員使用即時功能和發佈-訂閱模式輕鬆地建置 Web 應用程式。 任何需要在伺服器和客戶端之間或客戶端之間進行即時發佈-訂閱傳訊的案例,都可以使用 Azure Web PubSub 服務。 通常需要從伺服器輪詢或提交 HTTP 要求的傳統即時功能也可以使用 Azure Web PubSub 服務。

您可以在應用程式伺服器端使用此連結庫來管理 WebSocket 用戶端連線,如下圖所示:

溢位 。

  • 將訊息傳送至中樞和群組。
  • 將訊息傳送給特定用戶和連線。
  • 將使用者和連線組織成群組。
  • 關閉連線
  • 授與、撤銷和檢查現有連線的許可權

此處所用詞彙的詳細數據,請參閱 重要概念 一節。

原始程式碼 | 套件 (NPM) | API 參考檔, | 產品檔 | 範例

開始

目前支持的環境

先決條件

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

npm install @azure/web-pubsub

2.建立及驗證 WebPubSubServiceClient

import { WebPubSubServiceClient } from "@azure/web-pubsub";

const serviceClient = new WebPubSubServiceClient("<ConnectionString>", "<hubName>");

您也可以使用端點和 WebPubSubServiceClient來驗證 AzureKeyCredential:

import { AzureKeyCredential, WebPubSubServiceClient } from "@azure/web-pubsub";

const key = new AzureKeyCredential("<Key>");
const serviceClient = new WebPubSubServiceClient("<Endpoint>", key, "<hubName>");

或使用 Azure Active Directory WebPubSubServiceClient 驗證

  1. 安裝 @azure/identity 相依性
npm install @azure/identity
  1. 更新原始碼以使用 DefaultAzureCredential:
import { DefaultAzureCredential } from "@azure/identity";
import { WebPubSubServiceClient } from "@azure/web-pubsub";

const key = new DefaultAzureCredential();
const serviceClient = new WebPubSubServiceClient("<Endpoint>", key, "<hubName>");

重要概念

連接

連接也稱為用戶端或用戶端連線,代表連線至 Web PubSub 服務的個別 WebSocket 連線。 成功連線時,Web PubSub 服務會將唯一聯機標識符指派給此連線。

樞紐

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

群

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

使用者

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

消息

當用戶端連線時,它可以透過 WebSocket 連線,將訊息傳送至上游應用程式,或從上游應用程式接收訊息。

例子

取得客戶端啟動 WebSocket 連線的存取令牌

import { WebPubSubServiceClient } from "@azure/web-pubsub";
import { DefaultAzureCredential } from "@azure/identity";

const serviceClient = new WebPubSubServiceClient(
  "<Endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);

// Get the access token for the WebSocket client connection to use
let token = await serviceClient.getClientAccessToken();

// Or get the access token and assign the client a userId
token = await serviceClient.getClientAccessToken({ userId: "user1" });

// Or get the access token that the client will join group GroupA when it connects using the access token
token = await serviceClient.getClientAccessToken({ userId: "user1", groups: ["GroupA"] });

將訊息廣播至中樞中的所有連線

import { WebPubSubServiceClient } from "@azure/web-pubsub";
import { DefaultAzureCredential } from "@azure/identity";

const serviceClient = new WebPubSubServiceClient(
  "<Endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);

// Send a JSON message
await serviceClient.sendToAll({ message: "Hello world!" });

// Send a plain text message
await serviceClient.sendToAll("Hi there!", { contentType: "text/plain" });

// Send a binary message
const payload = new Uint8Array(10);
await serviceClient.sendToAll(payload.buffer);

使用 OData 篩選語法將訊息傳送至中樞中的所有連線

filter 語法的詳細數據,請參閱 Azure Web PubSub OData 篩選語法。

import { WebPubSubServiceClient, odata } from "@azure/web-pubsub";
import { DefaultAzureCredential } from "@azure/identity";

const serviceClient = new WebPubSubServiceClient(
  "<Endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);

// Send a JSON message to anonymous connections
await serviceClient.sendToAll({ message: "Hello world!" }, { filter: "userId eq null" });

// Send a text message to connections in groupA but not in groupB
const groupA = "groupA";
const groupB = "groupB";
await serviceClient.sendToAll("Hello world!", {
  contentType: "text/plain",
  // use plain text "'groupA' in groups and not('groupB' in groups)"
  // or use the odata helper method
  filter: odata`${groupA} in groups and not(${groupB} in groups)`,
});

將訊息傳送至群組中的所有連線

import { WebPubSubServiceClient } from "@azure/web-pubsub";
import { DefaultAzureCredential } from "@azure/identity";

const serviceClient = new WebPubSubServiceClient(
  "<Endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);

const groupClient = serviceClient.group("<groupName>");

// Add user to the group
await groupClient.addUser("user1");

// Send a JSON message
await groupClient.sendToAll({ message: "Hello world!" });

// Send a plain text message
await groupClient.sendToAll("Hi there!", { contentType: "text/plain" });

// Send a binary message
const payload = new Uint8Array(10);
await groupClient.sendToAll(payload.buffer);

傳送訊息給使用者的所有連線

import { WebPubSubServiceClient } from "@azure/web-pubsub";
import { DefaultAzureCredential } from "@azure/identity";

const serviceClient = new WebPubSubServiceClient(
  "<Endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);

// Send a JSON message
await serviceClient.sendToUser("user1", { message: "Hello world!" });

// Send a plain text message
await serviceClient.sendToUser("user1", "Hi there!", { contentType: "text/plain" });

// Send a binary message
const payload = new Uint8Array(10);
await serviceClient.sendToUser("user1", payload.buffer);

檢查群組是否有任何連線

import { WebPubSubServiceClient } from "@azure/web-pubsub";
import { DefaultAzureCredential } from "@azure/identity";

const serviceClient = new WebPubSubServiceClient(
  "<Endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);

const groupClient = serviceClient.group("<groupName>");

// close all the connections in the group
await groupClient.closeAllConnections({ reason: "<closeReason>" });

// check if the group has any connections
const hasConnections = await serviceClient.groupExists("<groupName>");

存取作業的原始 HTTP 回應

import { WebPubSubServiceClient } from "@azure/web-pubsub";
import { DefaultAzureCredential } from "@azure/identity";

const serviceClient = new WebPubSubServiceClient(
  "<Endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);

function onResponse(rawResponse) {
  console.log(rawResponse);
}

await serviceClient.sendToAll({ message: "Hello world!" }, { onResponse });

故障排除

啟用記錄

啟用記錄可能有助於找出有關失敗的實用資訊。 若要查看 HTTP 要求和回應的記錄,請將 AZURE_LOG_LEVEL 環境變數設定為 info。

export AZURE_LOG_LEVEL=verbose

或者,您可以在運行時間啟用記錄,方法是在 setLogLevel中呼叫 @azure/logger:

import { setLogLevel } from "@azure/logger";

setLogLevel("info");

如需如何啟用記錄的詳細指示,請參閱@azure/記錄器套件檔。

實時追蹤

從 Web PubSub 服務入口網站使用 即時追蹤 來檢視即時流量。

後續步驟

如需如何使用此連結庫的詳細範例,請參閱 範例 目錄。

貢獻

如果您想要參與此連結庫,請閱讀 參與指南,以深入瞭解如何建置和測試程序代碼。