Azure Web PubSub 服務 是一項 Azure 管理服務,幫助開發者輕鬆建置具備即時功能及發佈-訂閱模式的網頁應用程式。 任何需要伺服器與用戶端之間即時發佈-訂閱訊息,或用戶端間的情境,都可以使用 Azure Web PubSub 服務。 傳統的即時功能通常需要從伺服器輪詢或提交 HTTP 請求,也可以使用 Azure Web PubSub 服務。
JavaScript 提供兩個函式庫:服務客戶端函式庫與 express 中介軟體。 以下章節包含更多關於這些圖書館的資訊。
Azure Web PubSub 服務客戶端庫適用於 JavaScript
你可以在應用程式伺服器端使用這個函式庫來管理 WebSocket 用戶端的連線,如下圖所示:
- 發送訊息給中心和群組。
- 向特定使用者和連線發送訊息。
- 將使用者和連結組織成群組。
- 密切連結
- 授權、撤銷並檢查現有連線的權限
原始碼 | 封裝(NPM) | API 參考文件 | 產品文件 | 取樣
入門指南
目前支援的環境
先決條件
- Azure 訂用帳戶。
- 一個現有的 Azure Web PubSub 服務實例。
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>"
);
或者用 WebPubSubServiceClient 來驗證
- 安裝
@azure/identity相依性
npm install @azure/identity
- 更新原始碼以使用
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/記錄器套件。
即時追蹤
請使用Web PubSub服務入口網站的 即時追蹤(Live Trace )查看即時流量。
適用於 Express 的 Azure Web PubSub CloudEvents 處理常式
當 WebSocket 連線連接時,Web PubSub 服務會將連線生命週期與訊息轉換為 CloudEvents 格式的事件。 此函式庫提供一個快速中介軟體,用以處理代表 WebSocket 連線生命週期與訊息的事件,如下圖所示:
原始碼 | 封裝(NPM) | API 參考文件 | 產品文件 | 取樣
入門指南
目前支援的環境
- LTS 版本的 Node.js
- Express 版本 4.x.x 或更高版本
先決條件
- Azure 訂用帳戶。
- 一個現有的 Azure Web PubSub 端點。
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}`
)
);
表達範例
處理請求並 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服務入口網站的 即時追蹤(Live Trace )查看即時流量。
後續步驟
使用這些資源開始建置自己的應用程式: