DEV Community

Albert Bennett
Albert Bennett

Posted on • Updated on

How to: Azure PubSub Service

If you learned something new feel free to connect with me on linkedin or follow me on dev.to :)
Also if you'd like to skip to the code I have posted it here on my GitHub page.


Today I'd like to chat a bit about the Azure Web PubSub Service and what it can do. I got the opportunity to use this service last week and I think that it is really interesting tech especially if you need to stream data through a websocket and don't want to set up a websocket server.


So what is Azure PubSub?
It is a service in Azure that allows you to push data to a hub and subscribers of that hub can get the data. Below I have an image of how this works:
UntitledThis connection happens over wss which is a TCP protocol over port 443. Traditionally to do this you'd need to set up a websocket server and establish a connection with it to serve the data. Using this new Azure service really removes a lot of headaches with streaming data to clients.


About the Sample
What the sample that I am going to go through is going to do is:

  1. Allow the user to subscribe to a hub.
  2. Push data to our hub so that subscribers can see it via a http trigger function in the function app.
  3. Display the data from our hub.

Step 1
Firstly we need to create the Web PubSub Service. There is not much to it... see image below of what settings I used to set it up:
image And that's about it for our Azure Services. You don't need to tweak anything on the new service, it's good to go as is well.. for our purposes it is. You can set up a function app with an app service plan as well if you wanted to deploy the code later on but... I didn't want to for this sample.


Step 2
Next onto the project setup. What we need to do first is to create an C# Function App project:image I have chosen to use a http trigger but, you could have used a timer trigger as the function as well because we will be using a timer function to send data to our hub.
From here you need to install the following nuget packages:

  1. Azure.Messaging.WebPubSub
  2. Microsoft.Azure.WebJobs.Extensions.WebPubSub

These packages are in beta so you'll need to search for the preview packages. What these lets us do is to push messages to our hub and allows users to subscribe to a hub. Finally you'll need to add a connection string from your PubSub service to the local.settings.json file of your function app. You can find the connection string to the Web PubSub service by going to Keys > Connection String (under the 'Primary'). See screen shot below:
pubsub connection string I have left a sample of what my settings file looks like below after adding the connection string:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "WebPubSubConnectionString": "[your connection string]"
  }
}
Enter fullscreen mode Exit fullscreen mode



Step 3
The code for this is very straight forward.
We need a function to push data to our hub and a function to let users subscribe to our hub.
Here is the code to get users to subscribe to our hub:

    public static class Subscribe
    {
        [FunctionName("Subscribe")]
        public static WebPubSubConnection Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
            [WebPubSubConnection(Hub ="test")] WebPubSubConnection connection,ILogger log)
        {
            return connection;
        }
    }
Enter fullscreen mode Exit fullscreen mode

This function essentially establishes a connection to our hub and it returns a json response. Below is a sample response from the endpoint:

{
    "baseUrl": "[base URL]",
    "url": "[base URL with access token]",
    "accessToken": "[the access token]"
}
Enter fullscreen mode Exit fullscreen mode

The main value we want to make use of is the 'url' field. The value of this is our connection to the hub in the PubSub Service.
And here is the code to push data to our hub.

    public class PublishData
    {
        [FunctionName("PublishData")]
        public async Task Run([TimerTrigger("*/10 * * * * *")] TimerInfo myTimer, ILogger log,
            [WebPubSub(Hub = "test")] IAsyncCollector<WebPubSubOperation> operations)
        {
            await operations.AddAsync(new SendToAll
            {
                Message = BinaryData.FromString(DateTime.Now.ToShortTimeString()),
                DataType = MessageDataType.Text
            });
        }
    }
Enter fullscreen mode Exit fullscreen mode

Essentially what this is doing is sending the data to all subscribers of the hub defined in the binding of our function in our case 'test'.
With that being set up you can now get clients to subscribe to the hub and receive data being published to the hub in real time.
Ok, so there isn't much to see here we can see that the timer function is being triggered but, not much else:
image In the repo I have added a new function to the app that returns a html page. On that page there is a js function that connects to the websocket and returns the data in real time.
image And with that, you can see that data being received by the subscriber in real time.



Thanks for reading my post, and I'll see you in the next one.

Top comments (0)