這個快速入門會示範最快了解 Web PubSub 聊天如何實際運作的方法。 你在 Azure 入口網站產生一個客戶端存取 URL,然後用 client SDK 連接、建立房間,並在沒有伺服器程式碼的情況下發送訊息。
先決條件
- 一個 Azure Web PubSub 資源,已設定儲存空間並啟用聊天功能。 如果你還沒這麼做,請參考 「配置儲存」並啟用聊天功能。
- Node.js 版本 20 或更新。
從入口網站取得客戶端存取權杖
用戶端會以用戶端存取 URL 連接聊天中心,該 URL 包含其使用者身份。 為了快速測試,可以在傳送門裡生成一個。
- 在 Azure 入口網站中,開啟你的 Web PubSub 資源。
- 在左側功能表中,選取 金鑰 窗格,然後選取 用戶端 URL 產生器。
- 將 Hub 設為你新增的 聊天中樞 名稱,例如
chat。 - 將 使用者 ID 設為任意名稱,例如
alice。 聊天室會用這個作為你的使用者身份。 - 複製 Client Access 的網址。
安裝用戶端 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
在這個快速入門中,您使用了一個入口網站權杖。 生產方面,從你自己的伺服器發行代幣。 請參閱 「認證並連結客戶」。