Azure Web PubSubチャットを始めましょう

このクイックスタートは、Web PubSubチャットが動作しているかを最速で確認する方法を示しています。 AzureポータルでクライアントアクセスURLを作成し、クライアントSDKを使って接続し、部屋を作成し、サーバーコードを使わずにメッセージを送信します。

前提条件

ポータルからクライアントアクセストークンを取得してください

クライアントはユーザーIDを持つクライアントアクセスURLを持つチャットハブに接続します。 簡単なテストとして、ポータルで一つ生成してください。

  1. Azureポータルで、Web PubSubリソースを開きます。
  2. 左のメニューで キー ブレードを選択し、その後クライアント URLジェネレーターを選択します
  3. 例えば、 Hub を追加した チャットハブ の名前に設定してください。例えば chat
  4. ユーザーIDを任意の名前に設定してください。例えばalice。 チャットはこれをユーザーIDとして使います。
  5. クライアントアクセスのURLをコピーしてください。

Azureポータル内のクライアントURLジェネレーターのスクリーンショットで、ハブ、ユーザーID、生成されたクライアントアクセスURLを示しています。

クライアント SDK のインストール

プロジェクトを作成し、クライアントSDKをインストールします。

mkdir chat-quickstart
cd chat-quickstart
npm init -y
npm install @azure/web-pubsub-chat-client

つながり、部屋を作成し、メッセージを送信しましょう

次のコードを index.mjsとして保存します。 ポータルからコピーしたURLに <client-access-url> を置き換えてください。

import { ChatClient } from "@azure/web-pubsub-chat-client";

// Paste the client access URL you generated in the portal.
const clientAccessUrl = "<client-access-url>";

async function main() {
  // Connect to chat hub.
  const client = await ChatClient.start(clientAccessUrl);
  console.log(`Connected as ${client.userId}`);

  // Print messages as they arrive.
  client.on("message", (event) => {
    const message = event.message;
    console.log(`${message.createdBy}: ${message.content.text}`);
  });

  // Create a room. You're added to it automatically.
  const room = await client.createRoom("My first room", []);
  console.log(`Created room ${room.roomId}`);

  // Send a message to the room.
  await client.sendToRoom(room.roomId, "Hello, Chat!");

  // Read the room's history back from your storage.
  console.log("History:");
  for await (const message of client.listRoomMessages(room.roomId)) {
    console.log(`  ${message.createdBy}: ${message.content.text}`);
  }

  // Disconnect.
  await client.stop();
}

main().catch(console.error);

次のコマンドを実行します。

node index.mjs

次のような出力が表示されます。

Connected as alice
Created room <room-id>
alice: Hello, Chat!
History:
  alice: Hello, Chat!

Note

このクイックスタートではポータルトークンを使いました。 本番環境では、自分のサーバーからトークンを発行してください。 「 クライアントの認証と接続」をご覧ください。