共用方式為


適用於 JavaScript 的 Web PubSub 用戶端 SDK

注意

此處所用詞彙的詳細資料會在《重要概念》 一文中詳述。

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

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

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

Screenshot showing clients establishing WebSocket connection with a Web PubSub resource

開始使用

必要條件

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

npm install @azure/web-pubsub-client

2.使用您的 Web PubSub 資源連線

用戶端會使用 Client Access URL 來連線並進行服務驗證,這會遵循 wss://<service_name>.webpubsub.azure.com/client/hubs/<hub_name>?access_token=<token> 模式。 用戶端可有幾種方式來取得 Client Access URL。 在本快速入門中,您可以從顯示的 Azure 入口網站複製並貼上一個。 (針對生產環境,用戶端通常會取得在應用程式伺服器上產生的 Client Access URL查看詳細資料)

Screenshot showing how to get Client Access Url on Azure portal

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

範例

處理 connecteddisconnectedstopped 事件

Azure Web PubSub 會引發系統事件,例如 connecteddisconnectedstopped。 您可以註冊事件處理程式,以決定程式在引發事件時應該執行的動作。

  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 an event handler for the "stopped" event
client.on("stopped", () => {
  console.log(`Client has stopped`);
});

使用應用程式伺服器以程式設計方式產生 Client Access URL

在生產環境中,用戶端通常會從應用程式伺服器擷取 Client Access URL。 伺服器會保存您 Web PubSub 資源的 connection string,並從伺服器端程式庫 @azure/web-pubsub 產生 Client Access URL

1.應用程式伺服器

程式碼片段是應用程式伺服器的範例,會公開 /negotiate 端點,並傳回 Client Access 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


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

用戶端可以新增回撥,以取用來自應用程式伺服器或群組的訊息。

// 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", (e) => {
  console.log(`Received message ${e.message.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", (e) => {
    console.log(`Received message from ${e.message.group}: ${e.message.data}`);
});

注意

針對 group-message 事件,用戶端只能接收來自其已加入的群組之訊息。

處理重新加入失敗

當用戶端中斷連線且無法復原時,會在您的 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.joinGroup()client.leaveGroup()client.sendToGroup()client.sendEvent() 等作業有三次重試。 您可以透過 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});
}

JavaScript 搭售方案

若要在瀏覽器中使用此用戶端程式庫,您必須使用搭售方案。 如需如何建立搭售方案的詳細資訊,請參閱我們的 搭售方案文件

疑難排解

啟用記錄

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

export AZURE_LOG_LEVEL=verbose

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

即時追蹤

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