Azure Web PubSub サービス は、開発者がリアルタイム機能と発行/サブスクライブ パターンを使用して Web アプリケーションを簡単に構築するのに役立つ Azure マネージド サービスです。 サーバーとクライアント間、またはクライアント間でリアルタイムの発行/サブスクライブ メッセージングを必要とするシナリオでは、Azure Web PubSub サービスを使用できます。 サーバーからのポーリングや HTTP 要求の送信が必要な従来のリアルタイム機能でも、Azure Web PubSub サービスを使用できます。
次の図に示すように、アプリ サーバー側でこのライブラリを使用して WebSocket クライアント接続を管理できます。
オーバーフローoverflowをします。
- ハブとグループにメッセージを送信します。
- 特定のユーザーと接続にメッセージを送信します。
- ユーザーと接続をグループにまとめる。
- 接続を閉じる
- 既存の接続のアクセス許可を付与、取り消し、確認する
ここで使用する用語の詳細については、「主な概念」セクションで説明します。
ソース コード | パッケージ (NPM) | API リファレンス ドキュメント | 製品ドキュメント | サンプル
はじめ
現在サポートされている環境
前提 条件
- Azure サブスクリプション。
- 既存の Azure Web PubSub サービス インスタンス。
1. @azure/web-pubsub
パッケージをインストールする
npm install @azure/web-pubsub
2. WebPubSubServiceClient を作成して認証する
import { WebPubSubServiceClient } from "@azure/web-pubsub";
const serviceClient = new WebPubSubServiceClient("<ConnectionString>", "<hubName>");
エンドポイントと WebPubSubServiceClient
を使用して AzureKeyCredential
を認証することもできます。
import { AzureKeyCredential, WebPubSubServiceClient } from "@azure/web-pubsub";
const key = new AzureKeyCredential("<Key>");
const serviceClient = new WebPubSubServiceClient("<Endpoint>", key, "<hubName>");
または、WebPubSubServiceClient
を使用して を認証します
-
@azure/identity
依存関係をインストールする
npm install @azure/identity
-
DefaultAzureCredential
を使用するようにソース コードを更新します。
import { DefaultAzureCredential } from "@azure/identity";
import { WebPubSubServiceClient } from "@azure/web-pubsub";
const key = new DefaultAzureCredential();
const serviceClient = new WebPubSubServiceClient("<Endpoint>", key, "<hubName>");
主な概念
接続
接続 (クライアントまたはクライアント接続とも呼ばれます) は、Web PubSub サービスに接続されている個々の WebSocket 接続を表します。 正常に接続されると、Web PubSub サービスによって一意の接続 ID がこの接続に割り当てられます。
ハブ
ハブは、一連のクライアント接続の論理的な概念です。 通常は、チャット ハブや通知ハブなど、1 つの目的に 1 つのハブを使用します。 クライアント接続が作成されると、ハブに接続され、その有効期間中にそのハブに属します。 異なるアプリケーションで、異なるハブ名を使用して 1 つの Azure Web PubSub サービスを共有できます。
群
グループは、ハブへの接続のサブセットです。 必要に応じて、グループにクライアント接続を追加したり、グループからクライアント接続を削除したりできます。 たとえば、クライアントがチャット ルームに参加するとき、またはクライアントがチャット ルームを離れたとき、このチャット ルームはグループと見なすことができます。 クライアントは複数のグループに参加でき、グループには複数のクライアントを含めることができます。
利用者
Web PubSub への接続は、1 人のユーザーに属することができます。 1 人のユーザーが複数のデバイスまたは複数のブラウザー タブに接続されている場合など、ユーザーが複数の接続を持っている可能性があります。
メッセージ
クライアントが接続されると、WebSocket 接続を介してアップストリーム アプリケーションにメッセージを送信したり、アップストリーム アプリケーションからメッセージを受信したりできます。
例
クライアントが WebSocket 接続を開始するためのアクセス トークンを取得する
import { WebPubSubServiceClient } from "@azure/web-pubsub";
import { DefaultAzureCredential } from "@azure/identity";
const serviceClient = new WebPubSubServiceClient(
"<Endpoint>",
new DefaultAzureCredential(),
"<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"] });
ハブ内のすべての接続にメッセージをブロードキャストする
import { WebPubSubServiceClient } from "@azure/web-pubsub";
import { DefaultAzureCredential } from "@azure/identity";
const serviceClient = new WebPubSubServiceClient(
"<Endpoint>",
new DefaultAzureCredential(),
"<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 フィルター構文参照してください。
import { WebPubSubServiceClient, odata } from "@azure/web-pubsub";
import { DefaultAzureCredential } from "@azure/identity";
const serviceClient = new WebPubSubServiceClient(
"<Endpoint>",
new DefaultAzureCredential(),
"<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)`,
});
グループ内のすべての接続にメッセージを送信する
import { WebPubSubServiceClient } from "@azure/web-pubsub";
import { DefaultAzureCredential } from "@azure/identity";
const serviceClient = new WebPubSubServiceClient(
"<Endpoint>",
new DefaultAzureCredential(),
"<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);
ユーザーのすべての接続にメッセージを送信する
import { WebPubSubServiceClient } from "@azure/web-pubsub";
import { DefaultAzureCredential } from "@azure/identity";
const serviceClient = new WebPubSubServiceClient(
"<Endpoint>",
new DefaultAzureCredential(),
"<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);
グループに接続があるかどうかを確認する
import { WebPubSubServiceClient } from "@azure/web-pubsub";
import { DefaultAzureCredential } from "@azure/identity";
const serviceClient = new WebPubSubServiceClient(
"<Endpoint>",
new DefaultAzureCredential(),
"<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 応答にアクセスする
import { WebPubSubServiceClient } from "@azure/web-pubsub";
import { DefaultAzureCredential } from "@azure/identity";
const serviceClient = new WebPubSubServiceClient(
"<Endpoint>",
new DefaultAzureCredential(),
"<hubName>",
);
function onResponse(rawResponse) {
console.log(rawResponse);
}
await serviceClient.sendToAll({ message: "Hello world!" }, { onResponse });
トラブルシューティング
ログを有効にする
ログ記録を有効にすると、エラーに関する有用な情報を明らかにするのに役立つ場合があります。 HTTP 要求と応答のログを表示するには、AZURE_LOG_LEVEL
環境変数を info
に設定します。
export AZURE_LOG_LEVEL=verbose
または、setLogLevel
で @azure/logger
を呼び出すことによって、実行時にログを有効にすることもできます。
import { setLogLevel } from "@azure/logger";
setLogLevel("info");
ログを有効にする方法の詳細な手順については、@azure/logger パッケージのドキュメントを参照してください。
ライブ トレース
Web PubSub サービス ポータル ライブ トレース を使用して、ライブ トラフィックを表示します。
次の手順
このライブラリの使用方法の詳細な例については、ディレクトリ
貢献
このライブラリに投稿する場合は、コードをビルドしてテストする方法の詳細については、投稿ガイド を参照してください。
関連プロジェクト
- Microsoft Azure SDK for Javascript の
Azure SDK for JavaScript