次の方法で共有


JavaScript 用 Azure Web PubSub サービス クライアント ライブラリ - バージョン 1.1.1

Azure Web PubSub サービスは、開発者がリアルタイムの機能と発行-サブスクライブ パターンを利用して Web アプリケーションを簡単に作成できるようにするための Azure マネージド サービスです。 サーバーとクライアント間、またはクライアント間で、リアルタイムのパブリッシュ-サブスクライブ メッセージングを必要とするあらゆるシナリオに、Azure Web PubSub サービスを使用できます。 従来のリアルタイム機能は、多くの場合、サーバーからのポーリングや HTTP 要求の送信を必要としますが、そのようなリアルタイム機能にも Azure Web PubSub サービスを使用できます。

次の図に示すように、このライブラリをアプリ サーバー側で使用して、WebSocket クライアント接続を管理できます。

overflow

  • ハブとグループにメッセージを送信します。
  • 特定のユーザーと接続にメッセージを送信します。
  • ユーザーと接続をグループに整理します。
  • 接続を終了します
  • 既存の接続のアクセス許可を付与、取り消し、確認します

ここで使われている用語の詳細は、主な概念のセクションを参照してください。

ソース コード | パッケージ (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>");

または、Azure Active Directory を使用して をWebPubSubServiceClient認証する

  1. @azure/identity 依存関係をインストールします。
npm install @azure/identity
  1. DefaultAzureCredential を使用するようにソース コードを更新します。
const { WebPubSubServiceClient, AzureKeyCredential } = require("@azure/web-pubsub");
const { DefaultAzureCredential } = require("@azure/identity");

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

主要な概念

Connection

接続は、クライアントまたはクライアント接続とも呼ばれ、Web PubSub サービスに接続されている個々の WebSocket 接続を表します。 正常に接続されると、一意の接続 ID が Web PubSub サービスによってこの接続に割り当てられます。

ハブ

ハブは、一連のクライアント接続の論理的な概念です。 通常、"チャット" ハブや "通知" ハブなど、1 つの目的に 1 つのハブを使います。 クライアント接続は、作成されると 1 つのハブに接続され、その有効期間中はそのハブに属します。 異なるアプリケーションでは、異なるハブ名を使用して、1 つの Azure Web PubSub サービスを共有できます。

グループ

グループはハブへの接続のサブセットです。 必要な場合はいつでも、クライアント接続をグループに追加したり、グループからクライアント接続を削除したりできます。 たとえば、クライアントがチャット ルームに参加したり、クライアントがチャット ルームを離れたりするときに、このチャット ルームをグループと見なすことができます。 クライアントは複数のグループに参加できます。また、1 つのグループに複数のクライアントを含めることもできます。

User

Web PubSub への接続を 1 人のユーザーに属させることができます。 1 人のユーザーが複数のデバイスまたは複数のブラウザー タブに接続されている場合など、ユーザーが複数の接続を持つ場合があります。

Message

クライアントが接続されている場合は、WebSocket 接続を介して、アップストリーム アプリケーションにメッセージを送信したり、アップストリーム アプリケーションからメッセージを受信したりできます。

クライアントが 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" });

// 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" ] });

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

OData フィルター構文を使用してハブ内のすべての接続にメッセージを送信する

構文の詳細 filter については、「 Azure Web PubSub の OData フィルター構文」を参照してください。

const { WebPubSubServiceClient, odata } = require("@azure/web-pubsub");

const serviceClient = new WebPubSubServiceClient("<ConnectionString>", "<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)` 
  });

グループ内のすべての接続にメッセージを送信する

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

トラブルシューティング

ログの有効化

このライブラリの使用時にデバッグ ログを表示するには、次の環境変数を取得します。

  • SignalR クライアント ライブラリからデバッグ ログを取得する
export AZURE_LOG_LEVEL=verbose

ログを有効にする方法の詳細については、@azure/logger パッケージに関するドキュメントを参照してください。

ライブ トレース

ライブトラフィックを表示するには、Web PubSub サービス ポータルから ライブ トレースを使用します。

次のステップ

このライブラリの使用方法の詳細な例については、 samples ディレクトリを参照してください。

共同作成

このライブラリに投稿する場合、コードをビルドしてテストする方法の詳細については、投稿ガイドを参照してください。