開始使用 Azure Web PubSub 聊天

這個快速入門會示範最快了解 Web PubSub 聊天如何實際運作的方法。 你在 Azure 入口網站產生一個客戶端存取 URL,然後用 client SDK 連接、建立房間,並在沒有伺服器程式碼的情況下發送訊息。

先決條件

從入口網站取得客戶端存取權杖

用戶端會以用戶端存取 URL 連接聊天中心,該 URL 包含其使用者身份。 為了快速測試,可以在傳送門裡生成一個。

  1. 在 Azure 入口網站中,開啟你的 Web PubSub 資源。
  2. 在左側功能表中,選取 金鑰 窗格,然後選取 用戶端 URL 產生器。
  3. 將 Hub 設為你新增的 聊天中樞 名稱,例如 chat。
  4. 將 使用者 ID 設為任意名稱,例如 alice。 聊天室會用這個作為你的使用者身份。
  5. 複製 Client Access 的網址。

Azure 入口網站中用戶端 URL 產生器的截圖,顯示樞紐、使用者 ID 及產生的用戶端存取 URL。

安裝用戶端 SDK

建立一個專案並安裝客戶端 SDK。

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

連結、建立房間並發送訊息

將以下程式碼儲存為 index.mjs。 用你從入口網站複製的網址替換 <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

在這個快速入門中,您使用了一個入口網站權杖。 生產方面,從你自己的伺服器發行代幣。 請參閱 「認證並連結客戶」。