共用方式為


適用于 JavaScript 的 Azure Web PubSub 服務用戶端程式庫 - 1.1.1 版

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

const { WebPubSubServiceClient } = require("@azure/web-pubsub");

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

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

const { WebPubSubServiceClient, AzureKeyCredential } = require("@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
const { WebPubSubServiceClient, AzureKeyCredential } = require("@azure/web-pubsub");
const { DefaultAzureCredential } = require("@azure/identity");

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

重要概念

連線

「連線」也稱為用戶端或用戶端連線,代表連線到 Web PubSub 服務的個別 WebSocket 連線。 成功連線時,Web PubSub 服務會指派唯一的連線識別碼給此連線。

集線器

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

群組

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

User

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

訊息

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

範例

取得用戶端的存取權杖以啟動 WebSocket 連線

const { WebPubSubServiceClient } = require("@azure/web-pubsub");

const serviceClient = new WebPubSubServiceClient("<ConnectionString>", "<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" ] });

// return the token to the WebSocket client

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

const { WebPubSubServiceClient } = require("@azure/web-pubsub");

const serviceClient = new WebPubSubServiceClient("<ConnectionString>", "<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 篩選語法

const { WebPubSubServiceClient, odata } = require("@azure/web-pubsub");

const serviceClient = new WebPubSubServiceClient("<ConnectionString>", "<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)` 
  });

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

const { WebPubSubServiceClient } = require("@azure/web-pubsub");

const serviceClient = new WebPubSubServiceClient("<ConnectionString>", "<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);

將訊息傳送至某使用者的所有連線

const { WebPubSubServiceClient } = require("@azure/web-pubsub");

const serviceClient = new WebPubSubServiceClient("<ConnectionString>", "<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);

檢查群組是否有任何連線

const { WebPubSubServiceClient } = require("@azure/web-pubsub");
const WebSocket = require("ws");

const serviceClient = new WebPubSubServiceClient("<ConnectionString>", "<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 回應

const { WebPubSubServiceClient } = require("@azure/web-pubsub");

function onResponse(rawResponse) {
  console.log(rawResponse);
}
const serviceClient = new WebPubSubServiceClient("<ConnectionString>", "<hubName>");
await serviceClient.sendToAll({ message: "Hello world!" }, { onResponse });

疑難排解

啟用記錄

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

  • 從 SignalR 用戶端程式庫取得偵錯記錄
export AZURE_LOG_LEVEL=verbose

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

即時追蹤

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

下一步

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

參與

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