Azure Web PubSub 服務 是一項 Azure 管理服務,幫助開發者輕鬆建立具備即時功能及發佈-訂閱模式的網頁應用程式。 任何需要伺服器與用戶端之間即時發佈-訂閱訊息,或用戶端間的情境,都可以使用 Azure Web PubSub 服務。 傳統的即時功能通常需要從伺服器輪詢或提交 HTTP 請求,也可以使用 Azure Web PubSub 服務。
你可以在應用程式伺服器端使用這個函式庫來管理 WebSocket 用戶端的連線,如下圖所示:
使用此函式庫:
- 發送訊息給中心和群組。
- 向特定使用者和連線發送訊息。
- 將使用者和連結組織成群組。
- 密切連結
- 授權、撤銷並檢查現有連線的權限
原始程式碼 | 套件 | API 參考文件 | 產品文件 | 範例
入門指南
安裝套件
安裝 NuGet 的用戶端函式庫:
dotnet add package Azure.Messaging.WebPubSub
先決條件
- Azure 訂用帳戶。
- 一個現有的 Azure Web PubSub 服務實例。
建立和驗證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);
故障排除
設定主控台記錄
如果想要更深入了解您對服務提出的要求,您也可以啟用控制台記錄 。
後續步驟
使用這些資源開始建置自己的應用程式: