次の方法で共有


JavaScript 用 Web PubSub クライアント側 SDK

Note

ここで使われている用語の詳細は、主な概念の記事を参照してください。

クライアント側 SDK は、開発者のワークフローを高速化することを目的としています。具体的には、次のとおりです。

  • クライアント接続の管理を簡素化する
  • クライアント間でのメッセージの送信を簡素化する
  • クライアント接続の意図しない切断後に自動的に再試行する
  • 接続の切断からの復旧後に、数と順序を確実にしてメッセージを配信する

図に示すように、クライアントは Web PubSub リソースとの WebSocket 接続を確立します。

Screenshot showing clients establishing WebSocket connection with a Web PubSub resource

作業の開始

前提条件

1. @azure/web-pubsub-client パッケージをインストールする

npm install @azure/web-pubsub-client

2.Web PubSub リソースに接続する

クライアントは、Client Access URL を使用してサービスに接続して認証します。これは、 wss://<service_name>.webpubsub.azure.com/client/hubs/<hub_name>?access_token=<token> のパターンに従います。 クライアントには、Client Access URL を取得するいくつかの方法があります。 このクイック ガイドでは、Azure portal からコピーして貼り付けることができます。 (運用環境の場合には、通常、クライアントはアプリケーション サーバーで Client Access URL 生成されます。詳細を参照してください)

Screenshot showing how to get Client Access Url on Azure portal

図に示すように、クライアントには、group1 という名前の特定のグループにメッセージを送信して参加するためのアクセス許可があります。

// Imports the client libray
const { WebPubSubClient } = require("@azure/web-pubsub-client");

// Instantiates the client object
const client = new WebPubSubClient("<client-access-url>");

// Starts the client connection with your Web PubSub resource
await client.start();

// ...
// The client can join/leave groups, send/receive messages to and from those groups all in real-time

3.グループに参加する

クライアントは、参加しているグループからのみメッセージを受信できます。 コールバックを追加して、メッセージを受信するときに実行する処理のロジックを指定できます。

// ...continues the code snippet from above

// Specifies the group to join
let groupName = "group1";

// Registers a listener for the event 'group-message' early before joining a group to not miss messages
client.on("group-message", (e) => {
  console.log(`Received message: ${e.message.data}`);
});

// A client needs to join the group it wishes to receive messages from
await client.joinGroup(groupName);

4.メッセージをグループに送信する

// ...continues the code snippet from above

// Send a message to a joined group
await client.sendToGroup(groupName, "hello world", "text");

// In the Console tab of your developer tools found in your browser, you should see the message printed there.

connecteddisconnected および stopped イベントを処理します

Azure Web PubSub は、 connecteddisconnectedstopped などのシステム イベントを発生します。 イベント ハンドラーを登録して、イベントが発生したときにプログラムが実行する必要がある処理を決定できます。

  1. クライアントが Web PubSub リソースに正常に接続されると、connected イベントがトリガーされます。 このスニペットは、接続 IDを出力するだけです
client.on("connected", (e) => {
  console.log(`Connection ${e.connectionId} is connected.`);
});
  1. クライアントが切断され、接続の復旧に失敗すると、disconnected イベントがトリガーされます。 このスニペットは、単にメッセージを出力します。
client.on("disconnected", (e) => {
  console.log(`Connection disconnected: ${e.message}`);
});
  1. stopped イベントは、クライアントが切断、およびクライアントが再接続の試行を停止するときにトリガーされます。 これは通常、client.stop() が呼び出された後、または autoReconnect が無効になっているか、再接続を試行するための指定された制限に達した後に発生します。 クライアントを再起動する場合は、停止されたイベントで client.start() を呼び出すことができます。
// Registers an event handler for the "stopped" event
client.on("stopped", () => {
  console.log(`Client has stopped`);
});

アプリケーション サーバーを使用して、プログラムで Client Access URL を生成する

運用環境では、通常、クライアントはアプリケーション サーバーから Client Access URL をフェッチします。 サーバーは、Web PubSub リソースへの connection string を保持し、サーバー側ライブラリ @azure/web-pubsub のヘルプを使用して Client Access URL を生成します。

1.アプリケーション サーバー

コード スニペットは、/negotiate エンドポイントを公開するアプリケーション サーバーの例で、Client Access URL を返します。

// This code snippet uses the popular Express framework
const express = require('express');
const app = express();
const port = 8080;

// Imports the server library, which is different from the client library
const { WebPubSubServiceClient } = require('@azure/web-pubsub');
const hubName = 'sample_chat';

const serviceClient = new WebPubSubServiceClient("<web-pubsub-connectionstring>", hubName);

// Note that the token allows the client to join and send messages to any groups. It is specified with the "roles" option.
app.get('/negotiate', async (req, res) => {
  let token = await serviceClient.getClientAccessToken({roles: ["webpubsub.joinLeaveGroup", "webpubsub.sendToGroup"] });
  res.json({
    url: token.url
  });
});

app.listen(port, () => console.log(`Application server listening at http://localhost:${port}/negotiate`));

2.クライアント側

const { WebPubSubClient } = require("@azure/web-pubsub-client")

const client = new WebPubSubClient({
  getClientAccessUrl: async () => {
    let value = await (await fetch(`/negotiate`)).json();
    return value.url;
  }
});

await client.start();

Note

このサンプルの完全なコードについては、「samples-browser」を参照してください。


クライアントがアプリケーション サーバー、または参加済みグループからのメッセージを使用する

クライアントは、アプリケーション サーバーまたはグループからメッセージを取り込むためのコールバックを追加できます。

// Registers a listener for the "server-message". The callback is invoked when your application server sends message to the connectionID, to or broadcast to all connections.
client.on("server-message", (e) => {
  console.log(`Received message ${e.message.data}`);
});

// Registers a listener for the "group-message". The callback is invoked when the client receives a message from the groups it has joined.
client.on("group-message", (e) => {
    console.log(`Received message from ${e.message.group}: ${e.message.data}`);
});

Note

group-message イベントに対して、クライアントは参加しているグループからのみメッセージを受信できます。

再結合エラーを処理する

クライアントが切断され、復旧に失敗すると、すべてのグループ コンテキストが Web PubSub リソースでクリーンアップされます。 つまり、クライアントが再接続するときは、グループに再参加する必要があります。 既定で、クライアントは autoRejoinGroup オプションが有効になっています。

ただし、autoRejoinGroup の制限に注意してください。

  • クライアントは、サーバー側のコードによって参加しているのではなく、クライアント コードによって結合されたグループのみを再結合できます。
  • グループに参加する権限がクライアントにないなど、さまざまな理由により、「グループの再参加」操作が失敗する可能性があります。 このような場合、このエラーを処理するためのコールバックを追加する必要があります。
// By default autoRejoinGroups=true. You can disable it by setting to false.
const client = new WebPubSubClient("<client-access-url>", { autoRejoinGroups: true });

// Registers a listener to handle "rejoin-group-failed" event
client.on("rejoin-group-failed", e => {
  console.log(`Rejoin group ${e.group} failed: ${e.error}`);
})

再試行

既定では、client.joinGroup()client.leaveGroup()client.sendToGroup()client.sendEvent() などの操作では 3 回再試行できます。 messageRetryOptions を通じて構成できます. すべての再試行が失敗した場合、エラーがスローされます。 前の再試行と同じ ackId を渡すことで再試行を続けることができるため、Web PubSub サービスは操作を重複除去するのに役立ちます。

try {
  await client.joinGroup(groupName);
} catch (err) {
  let id = null;
  if (err instanceof SendMessageError) {
    id = err.ackId;
  }
  await client.joinGroup(groupName, {ackId: id});
}

JavaScript バンドル

ブラウザーでこのクライアント ライブラリを使用するには、bundler を使用する必要があります。 バンドルを作成する方法の詳細については、「バンドルに関するドキュメント」を参照してください。

トラブルシューティング

ログの有効化

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

export AZURE_LOG_LEVEL=verbose

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

ライブ トレース

Azure portal からライブ トレース ツールを使って、Web PubSub リソースを介してライブ メッセージ トラフィックを検査します。