分享方式:


適用於 Azure Web PubSub 的 JavaScript SDK

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

JavaScript 提供兩個程式庫:服務用戶端程式庫和 Express 中介軟體。 下列各節包含這些程式庫的詳細資訊。

適用於 JavaScript 的 Azure Web PubSub 服務用戶端程式庫

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

The overflow diagram shows the overflow of using the service client library.

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

原始程式碼 | 套件 (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>"
);

或使用 Microsoft Entra ID 驗證 WebPubSubServiceClient

  1. 安裝 @azure/identity 相依性
npm install @azure/identity
  1. 更新原始程式碼以使用DefaultAzureCredential
const {
  WebPubSubServiceClient,
  AzureKeyCredential,
} = require("@azure/web-pubsub");

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

範例

取得用戶端的存取權杖以啟動 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" });

// 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);

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

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: FullOperationResponse): void {
  console.log(rawResponse);
}
const serviceClient = new WebPubSubServiceClient(
  "<ConnectionString>",
  "<hubName>"
);
await serviceClient.sendToAll({ message: "Hello world!" }, { onResponse });

服務用戶端疑難排解

啟用記錄

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

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

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

即時追蹤

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

適用於 Express 的 Azure Web PubSub CloudEvents 處理常式

WebSocket 連線連接成功時,Web PubSub 服務會將連線生命週期和訊息轉換成 CloudEvents 格式的事件。 此程式庫提供 Express 中介軟體,可處理代表 WebSocket 連線生命週期和訊息的事件,如下圖所示:

The overflow diagram shows the overflow of using the event handler middleware.

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

開始使用

目前支援的環境

必要條件

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

npm install @azure/web-pubsub-express

2.建立 WebPubSubEventHandler

const express = require("express");

const { WebPubSubEventHandler } = require("@azure/web-pubsub-express");
const handler = new WebPubSubEventHandler("chat");

const app = express();

app.use(handler.getMiddleware());

app.listen(3000, () =>
  console.log(
    `Azure WebPubSub Upstream ready at http://localhost:3000${handler.path}`
  )
);

Express 範例

處理 connect 要求並指派 <userId>

const express = require("express");

const { WebPubSubEventHandler } = require("@azure/web-pubsub-express");
const handler = new WebPubSubEventHandler("chat", {
  handleConnect: (req, res) => {
    // auth the connection and set the userId of the connection
    res.success({
      userId: "<userId>",
    });
  },
  allowedEndpoints: ["https://<yourAllowedService>.webpubsub.azure.com"],
});

const app = express();

app.use(handler.getMiddleware());

app.listen(3000, () =>
  console.log(
    `Azure WebPubSub Upstream ready at http://localhost:3000${handler.path}`
  )
);

只允許指定的端點

const express = require("express");

const { WebPubSubEventHandler } = require("@azure/web-pubsub-express");
const handler = new WebPubSubEventHandler("chat", {
  allowedEndpoints: [
    "https://<yourAllowedService1>.webpubsub.azure.com",
    "https://<yourAllowedService2>.webpubsub.azure.com",
  ],
});

const app = express();

app.use(handler.getMiddleware());

app.listen(3000, () =>
  console.log(
    `Azure WebPubSub Upstream ready at http://localhost:3000${handler.path}`
  )
);

設定自訂事件處理常式路徑

const express = require("express");

const { WebPubSubEventHandler } = require("@azure/web-pubsub-express");
const handler = new WebPubSubEventHandler("chat", {
  path: "/customPath1",
});

const app = express();

app.use(handler.getMiddleware());

app.listen(3000, () =>
  // Azure WebPubSub Upstream ready at http://localhost:3000/customPath1
  console.log(
    `Azure WebPubSub Upstream ready at http://localhost:3000${handler.path}`
  )
);

設定和讀取連線狀態

const express = require("express");

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

const handler = new WebPubSubEventHandler("chat", {
  handleConnect(req, res) {
    // You can set the state for the connection, it lasts throughout the lifetime of the connection
    res.setState("calledTime", 1);
    res.success();
  },
  handleUserEvent(req, res) {
    var calledTime = req.context.states.calledTime++;
    console.log(calledTime);
    // You can also set the state here
    res.setState("calledTime", calledTime);
    res.success();
  },
});

const app = express();

app.use(handler.getMiddleware());

app.listen(3000, () =>
  console.log(
    `Azure WebPubSub Upstream ready at http://localhost:3000${handler.path}`
  )
);

疑難排解

啟用記錄

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

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

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

即時追蹤

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

下一步

使用這些資源開始建置您自己的應用程式: