Share via


來自用戶端的事件通知

在前三篇「快速入門」文章中,我們學到了兩種使用 Web PubSub 進行大規模 (百萬以上) 即時傳訊的實用通訊模式。

  • 在用戶端之間 Pub/Sub,讓您的應用程式伺服器免於應付管理持續連線的複雜性
  • 當有新資料可用時,立即從應用程式伺服器推送訊息至用戶端

在本快速入門指南中,我們會了解 Web PubSub 的事件系統,以便您的應用程式伺服器可以回應事件,例如當

  • 用戶端為 connected
  • 用戶端傳送需要進一步處理的 message

GIF of application server receiving client events.

必要條件

  • Web PubSub 資源。 若您尚未建立,您可以遵循下列指引:建立 Web PubSub 資源
  • 程式碼編輯器,例如 Visual Studio Code
  • 針對您打算使用的語言安裝相依性

建立應用程式

Web PubSub 是應用程式伺服器的獨立服務。 雖然您的應用程式會保留其作為傳統 HTTP 伺服器的角色,但 Web PubSub 會負責處理在應用程式伺服器與用戶端之間傳遞的即時訊息。 我們會先建立用戶端程式,然後建立伺服器程式。

建立用戶端

1.建立用戶端應用程式的目錄

mkdir eventHandlerDemo
cd eventHandlerDemo

# The SDK is available as an NPM module.
npm install @azure/web-pubsub-client

2.連線到 Web PubSub

用戶端 (無論是瀏覽器、行動裝置應用程式或 IoT 裝置) 都會使用用戶端存取 URL 來連線及驗證您的資源。 此 URL 遵循 wss://<service_name>.webpubsub.azure.com/client/hubs/<hub_name>?access_token=<token> 模式。 用戶端可以有幾種方式來取得用戶端存取 URL。 在本快速入門中,您可以從 Azure 入口網站複製並貼上 URL,如下圖所示。 最佳做法是不要在程式碼中對用戶端存取 URL 進行硬式編碼。 在實際執行環境中,我們通常會設定應用程式伺服器視需要傳回此 URL。 此做法在產生用戶端存取 URL 中有詳細說明。

The diagram shows how to get Client Access Url.

建立名為 client.js 的檔案並新增下列程式碼

const { WebPubSubClient } = require("@azure/web-pubsub-client");
// Instantiates the client object 
// <client-access-url> is copied from Azure portal mentioned above.
const client = new WebPubSubClient("<client-access-url>");

// Registers a handler to the "connected" event
client.on("connected", (e) => {
  console.log(`Connection ${e.connectionId} is connected.`);
});

// You must invoke start() on the client object 
// to establish connection with your Web PubSub resource
client.start();

建立應用程式伺服器

1.安裝 express.js 和 Web PubSub 伺服器 SDK

npm init -y
npm install --save express

# Installs the middleware from Web PubSub. This middleware will set up an endpoint for you.
npm install --save @azure/web-pubsub-express 

2.建立名為「server.js」的新檔案,以設定空的 Express 應用程式

const express = require("express");

const app = express();

app.listen(8080, () => console.log('Server started, listening on port 8080'));

3.處理事件

使用 Web PubSub 時,當用戶端發生某些活動 (例如,當用戶端與您的 Web PubSub 資源已 connecteddisconnected),您的應用程式伺服器可以設定處理常式來回應這些事件。

以下是兩個值得注意的使用案例:
  • 當用戶端已連線時,您可以將此狀態廣播給所有已連線的用戶端
  • 當用戶端將訊息傳送至您的 Web PubSub 資源時,您可以將訊息保存在您選擇的資料庫中
const express = require("express");
const { WebPubSubEventHandler } = require("@azure/web-pubsub-express");

const app = express();

const HUB_NAME = "myHub1";

let handler = new WebPubSubEventHandler(HUB_NAME, {
  path: '/eventhandler', // Exposes an endpoint 
  onConnected: async (req) => {
    console.log(`${req.context.userId} connected`);
  }, 
});

// Registers the middleware with the express app
app.use(handler.getMiddleware());

app.listen(8080, () => console.log('Server started, listening on port 8080'));

如上述程式碼中所設定,當用戶端與您的 Web PubSub 資源連線時,Web PubSub 會在路徑 /eventhandler 上叫用應用程式伺服器所提供的 Webhook。 在這裡,我們只需在使用者連線時,將 userId 列印到主控台。

公開 localhost

執行程式,它應該在連接埠 8080localhost 上執行。 基於我們的目的,這表示您無法在網際網路上連線到您的本機 Express 應用程式。 因此,Web PubSub 無法叫用在路徑 /eventhandler 上提供的 Webhook。

有兩種方式可將流量路由傳送至 localhost,一種是使用 ngrokTunnelRelay 等工具來公開可在網際網路上存取的 localhost。 另一種方式 (也就是建議的方式) 是使用 awps-tunnel,透過工具將來自 Web PubSub 服務的流量經由通道送到您的本機伺服器。

1.下載並安裝 awps-tunnel

此工具會在 Node.js 16 版或更新版本上執行。

npm install -g @azure/web-pubsub-tunnel-tool

2.使用服務連接字串並執行

export WebPubSubConnectionString="<your connection string>"
awps-tunnel run --hub myHub1 --upstream http://localhost:8080

在您的 Web PubSub 資源上設定事件處理常式

現在,我們需要讓您的 Web PubSub 資源知道此 Webhook URL。 您可以從 Azure 入口網站或 Azure CLI 設定事件處理常式。

  1. 從功能表中選取 [設定],然後選取 [新增]Screenshot of Azure Web PubSub Configure Event Handler - menu.

  2. 輸入中樞名稱。 為了我們的目的,請輸入 "myHub1",然後選取 [新增]

  3. 在事件處理常式頁面中,設定下列欄位,在使用 awps-tunnel 工具時,URL 範本會使用 tunnel 配置,後面接著路徑:tunnel:///eventhandlerScreenshot of Azure Web PubSub Configure Event Handler - details.

  4. 儲存組態Screenshot of Azure Web PubSub Configure Event Handler - save.

執行程式

啟動應用程式伺服器

node server.js

啟動用戶端程式

node client.js

觀察結果

您應該會看到 userId 列印至主控台。

處理訊息事件

除了 connectconnecteddisconnected 等系統事件之外,用戶端也可以傳送自訂事件。

修改用戶端程式

停止您的用戶端程式,並將下列程式碼新增至 client.js

// ...code from before

client.start();

// The name of the event is message and the content is in text format.
client.sendEvent("message", "sending custom event!", "text");

修改伺服器程式

停止您的用戶端程式,並將下列程式碼新增至 server.js

// ... code from before

let handler = new WebPubSubEventHandler(HUB_NAME, {
  path: "/eventhandler",
  onConnected: async (req) => {
    console.log(`"${req.context.userId}" is connected.`);
  },
  // This handler function will handle user system
  handleUserEvent: async (req, res) => {
    if (req.context.eventName === "message") {
      console.log(`Received message: ${req.data}`);
      // Additional logic to process the data,
      // e.g save message content to database 
      // or broadcast the message to selected clients.
    }
  },
});

//... code from before

再次啟動用戶端程式和伺服器程式

您應該會看到 userIdReceived message: sending custom event! 都列印至主控台。

摘要

本教學課程提供有關事件系統在 Web PubSub 中運作方式的基本概念。 在真實世界中,事件系統可協助您實作更多邏輯來處理系統和使用者產生的事件。

下一步