共用方式為


適用於 .NET 的 Azure Web PubSub 服務用戶端程式庫

Azure Web PubSub 服務是一項 Azure 受控服務,可協助開發人員輕鬆建置具有即時功能和發佈/訂閱模式的 Web 應用程式。 任何需要伺服器與用戶端之間或用戶端之間即時發佈-訂閱傳訊的案例,都可以使用 Azure Web PubSub 服務。 通常需要從伺服器輪詢或提交 HTTP 要求的傳統即時功能,也可以使用 Azure Web PubSub 服務。

您可以在應用程式伺服器端使用此程式庫來管理 WebSocket 用戶端連線,如下圖所示:

The overflow diagram shows the overflow of using the service client library.

使用此程式庫來:

  • 傳送訊息至中樞和群組。
  • 傳送訊息至特定使用者和連線。
  • 將使用者和連線組織成群組。
  • 關閉連線
  • 授與、撤銷和檢查現有連線的權限

原始程式碼 | 套件 | API 參考文件 | 產品文件 | 範例

開始使用

Install the package

NuGet 安裝用戶端程式庫:

dotnet add package Azure.Messaging.WebPubSub

必要條件

建立和驗證 WebPubSubServiceClient

若要與此服務互動,您必須建立 WebPubSubServiceClient 類別的執行個體。 若要達成此需求,必須要有連接字串或金鑰 (您可在 Azure 入口網站中加以存取)。

var serviceClient = new WebPubSubServiceClient(new Uri(endpoint), "some_hub", new AzureKeyCredential(key));

範例

將文字簡訊廣播至所有用戶端

var serviceClient = new WebPubSubServiceClient(new Uri(endpoint), "some_hub", new AzureKeyCredential(key));

serviceClient.SendToAll("Hello World!");

將 JSON 訊息廣播至所有用戶端

var serviceClient = new WebPubSubServiceClient(new Uri(endpoint), "some_hub", new AzureKeyCredential(key));

serviceClient.SendToAll(RequestContent.Create(
        new
        {
            Foo = "Hello World!",
            Bar = 42
        }),
        ContentType.ApplicationJson);

將二進位訊息廣播至所有用戶端

var serviceClient = new WebPubSubServiceClient(new Uri(endpoint), "some_hub", new AzureKeyCredential(key));

Stream stream = BinaryData.FromString("Hello World!").ToStream();
serviceClient.SendToAll(RequestContent.Create(stream), ContentType.ApplicationOctetStream);

疑難排解

設定主控台記錄

如果您想要深入了解您對服務提出的要求,也可以啟用主控台記錄

下一步

使用這些資源開始建置您自己的應用程式: