Azure Web PubSub サービス は、開発者がリアルタイム機能と発行/サブスクライブ パターンを使用して Web アプリケーションを簡単に構築するのに役立つ Azure マネージド サービスです。 サーバーとクライアント間、またはクライアント間でリアルタイムの発行/サブスクライブ メッセージングを必要とするシナリオでは、Azure Web PubSub サービスを使用できます。 サーバーからのポーリングや HTTP 要求の送信が必要な従来のリアルタイム機能でも、Azure Web PubSub サービスを使用できます。
JavaScript には、サービス クライアント ライブラリと高速ミドルウェアの 2 つのライブラリが用意されています。 以下のセクションでは、これらのライブラリの詳細について説明します。
JavaScript 用 Azure Web PubSub サービス クライアント ライブラリ
次の図に示すように、アプリ サーバー側でこのライブラリを使用して 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>"
);
エンドポイントとWebPubSubServiceClientを使用して、AzureKeyCredentialを認証することもできます。
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/logger パッケージに関するドキュメントを参照してください。
ライブ トレース
Web PubSub サービス ポータルから ライブ トレース を使用して、ライブ トラフィックを表示します。
Express 用 Azure Web Pubsub CloudEvents ハンドラー
WebSocket 接続が接続されると、Web PubSub サービスは接続ライフサイクルとメッセージを CloudEvents 形式のイベントに変換します。 このライブラリは、次の図に示すように、WebSocket 接続のライフサイクルとメッセージを表すイベントを処理する高速ミドルウェアを提供します。
ソース コード | パッケージ (NPM) | API リファレンス ドキュメント | 製品ドキュメント | サンプル
作業の開始
現在サポートされている環境
- Node.js の LTS バージョン
- 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 サービス ポータルから ライブ トレース を使用して、ライブ トラフィックを表示します。
次のステップ
これらのリソースを使用して、独自のアプリケーションの構築を開始します。