Azure Web PubSub service client library for .NET
Azure Web PubSub Service is an Azure-managed service that helps developers easily build web applications with real-time features and publish-subscribe pattern. Any scenario that requires real-time publish-subscribe messaging between server and clients or among clients can use Azure Web PubSub service. Traditional real-time features that often require polling from server or submitting HTTP requests can also use Azure Web PubSub service.
You can use this library in your app server side to manage the WebSocket client connections, as shown in below diagram:
Use this library to:
- Send messages to hubs and groups.
- Send messages to particular users and connections.
- Organize users and connections into groups.
- Close connections
- Grant, revoke, and check permissions for an existing connection
Source code | Package | API reference documentation | Product documentation | Samples
Getting started
Install the package
Install the client library from NuGet:
dotnet add package Azure.Messaging.WebPubSub
Prerequisites
- An Azure trial subscription.
- An existing Azure Web PubSub service instance.
Create and authenticate a WebPubSubServiceClient
In order to interact with the service, you'll need to create an instance of the WebPubSubServiceClient
class. To make this possible, you'll need the connection string or a key, which you can access in the Azure portal.
var serviceClient = new WebPubSubServiceClient(new Uri(endpoint), "some_hub", new AzureKeyCredential(key));
Examples
Broadcast a text message to all clients
var serviceClient = new WebPubSubServiceClient(new Uri(endpoint), "some_hub", new AzureKeyCredential(key));
serviceClient.SendToAll("Hello World!");
Broadcast a JSON message to all clients
var serviceClient = new WebPubSubServiceClient(new Uri(endpoint), "some_hub", new AzureKeyCredential(key));
serviceClient.SendToAll(RequestContent.Create(
new
{
Foo = "Hello World!",
Bar = 42
}),
ContentType.ApplicationJson);
Broadcast a binary message to all clients
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);
Troubleshooting
Setting up console logging
You can also enable console logging if you want to dig deeper into the requests you're making against the service.
Next steps
Use these resources to start building your own application: