Tutorial: Publish and subscribe messages using WebSocket API and Azure Web PubSub service SDK

The Azure Web PubSub service helps you easily build real-time web messaging applications. In this tutorial, you learn how to subscribe to the service using the WebSocket API and publish messages using the Web PubSub service SDK.

In this tutorial, you learn how to:

  • Create a Web PubSub service instance
  • Generate the full URL to establish the WebSocket connection
  • Create a Web PubSub subscriber client to receive messages using the standard WebSocket protocol
  • Create a Web PubSub publisher client to publish messages using the Web PubSub service SDK

Prerequisites

  • An Azure subscription, create a free account.
  • A Bash command shell. Use either a local shell or the Bash environment in Azure Cloud Shell.
  • If running on your local machine Install the Azure CLI.

You can use the Windows cmd.exe command shell instead of a Bash shell to run the commands in this tutorial.

If you're creating the project on a local machine, you need to install the dependencies for the language you're using:

Important

Raw connection strings appear in this article for demonstration purposes only.

A connection string includes the authorization information required for your application to access Azure Web PubSub service. The access key inside the connection string is similar to a root password for your service. In production environments, always protect your access keys. Use Azure Key Vault to manage and rotate your keys securely and secure your connection with WebPubSubServiceClient.

Avoid distributing access keys to other users, hard-coding them, or saving them anywhere in plain text that is accessible to others. Rotate your keys if you believe they may have been compromised.

Prepare your environment

Azure CLI setup for local development

Follow these steps to set up Azure CLI and your project environment.

  1. Open a command shell.

  2. Upgrade to the latest version of the Azure CLI.

    az upgrade
    
  3. Install the Azure CLI extension for Web PubSub.

    az extension add --name webpubsub
    
  4. Sign in to Azure CLI. Following the prompts, enter your Azure credentials.

    az login
    

Create a resource group

A resource group is a logical container into which Azure resources are deployed and managed. Use the az group create command to create a resource group named myResourceGroup in the eastus location.

az group create --name myResourceGroup --location EastUS

1. Create an Azure Web PubSub instance

Create a Web PubSub instance

To create a Web PubSub instance in the resource group you created, use the Azure CLI az webpubsub create command. The following command creates a Free Web PubSub resource under resource group myResourceGroup in EastUS:

Each Web PubSub resource must have a unique name. Replace <your-unique-resource-name> with the name of your Web PubSub instance in the following command.

az webpubsub create --resource-group myResourceGroup --name <your-unique-resource-name> --location EastUS --sku Free_F1

The output of this command shows properties of the newly created resource. Take note of the following properties:

  • name: The Web PubSub name you provided in the --name parameter above.
  • hostName: In the example, the host name is <your-unique-resource-name>.webpubsub.azure.com/.

At this point, your Azure account is the only one authorized to perform any operations on this new resource.

Get the connection string

Use the Azure CLI az webpubsub key command to get the ConnectionString of the service. Replace the <your-unique-resource-name> placeholder with the name of your Azure Web PubSub instance.

az webpubsub key show --resource-group myResourceGroup --name <your-unique-resource-name> --query primaryConnectionString --output tsv

Copy the connection string to use later.

Create a subscriber client

Clients connect to the Azure Web PubSub service through the standard WebSocket protocol using JSON Web Token (JWT) authentication. The service SDK provides helper methods to generate the token. In this tutorial, the subscriber directly generates the token from ConnectionString. In real applications, a server-side application usually handles the authentication/authorization workflow. To better understand the workflow, see the tutorial Build a chat app.

Raw connection strings appear in this article for demonstration purposes only. In production environments, always protect your access keys. Use Azure Key Vault to manage and rotate your keys securely and secure your connection with WebPubSubServiceClient.

  1. First, create a project directory named subscriber for this project and install required dependencies:

    • The package Websocket.Client is a third-party package supporting WebSocket connections. You can use any API/library that supports WebSocket.
    • The SDK package Azure.Messaging.WebPubSub helps to generate the JWT token.
    mkdir subscriber
    cd subscriber
    dotnet new console
    dotnet add package Websocket.Client --version 4.3.30
    dotnet add package Azure.Messaging.WebPubSub --version 1.0.0
    
  2. Replace the code in the Program.cs with the following code that connects to the service:

    using System;
    using System.Threading.Tasks;
    
    using Azure.Messaging.WebPubSub;
    
    using Websocket.Client;
    
    namespace subscriber
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                if (args.Length != 2)
                {
                    Console.WriteLine("Usage: subscriber <connectionString> <hub>");
                    return;
                }
                var connectionString = args[0];
                var hub = args[1];
    
                // Either generate the URL or fetch it from server or fetch a temp one from the portal
                var serviceClient = new WebPubSubServiceClient(connectionString, hub);
                var url = serviceClient.GetClientAccessUri();
    
                using (var client = new WebsocketClient(url))
                {
                    // Disable the auto disconnect and reconnect because the sample would like the client to stay online even no data comes in
                    client.ReconnectTimeout = null;
                    client.MessageReceived.Subscribe(msg => Console.WriteLine($"Message received: {msg}"));
                    await client.Start();
                    Console.WriteLine("Connected.");
                    Console.Read();
                }
            }
        }
    }
    
    

    The code creates a WebSocket connection that is connected to a hub in Web PubSub. A hub is a logical unit in Web PubSub where you can publish messages to a group of clients. Key concepts contains the detailed explanation about the terms used in Web PubSub.

    The Web PubSub service uses JSON Web Token (JWT) authentication. The sample code uses WebPubSubServiceClient.GetClientAccessUri() in Web PubSub SDK to generate a URL to the service that contains the full URL with a valid access token.

    After the connection is established, your client receives messages through the WebSocket connection. The client uses client.MessageReceived.Subscribe(msg => ...)); to listen for incoming messages.

  3. To start the subscriber, run the following command replacing <Web-PubSub-connection-string> with the connection string you copied earlier:

    dotnet run <Web-PubSub-connection-string> "myHub1"
    

2. Publish messages using service SDK

Create a publisher using the Azure Web PubSub SDK to publish a message to the connected client. For this project, you need to open another command shell.

  1. First, create a project directory named publisher and install required dependencies:

    mkdir publisher
    cd publisher
    dotnet new console
    dotnet add package Azure.Messaging.WebPubSub
    
  2. Update the Program.cs file to use the WebPubSubServiceClient class and send messages to the clients.

    using System;
    using System.Threading.Tasks;
    using Azure.Messaging.WebPubSub;
    
    namespace publisher
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                if (args.Length != 3) {
                    Console.WriteLine("Usage: publisher <connectionString> <hub> <message>");
                    return;
                }
                var connectionString = args[0];
                var hub = args[1];
                var message = args[2];
    
                // Either generate the token or fetch it from server or fetch a temp one from the portal
                var serviceClient = new WebPubSubServiceClient(connectionString, hub);
                await serviceClient.SendToAllAsync(message);
            }
        }
    }
    
    

    The SendToAllAsync() call simply sends a message to all connected clients in the hub.

  3. Send a message by running the following command. Replace <Web-PubSub-connection-string> with the connection string you copied earlier.

    dotnet run <Web-PubSub-connection-string> "myHub1" "Hello World"
    
  4. Verify that the subscriber's command shell receives the message:

    Message received: Hello World
    

Cleanup

You can delete the resources that you created in this quickstart by deleting the resource group that contains them.

az group delete --name myResourceGroup --yes

If you aren't planning to continue using Azure Cloud Shell, you can avoid accumulating costs by deleting the resource group that contains the associated the storage account. The resource group is named cloud-shell-storage-<your-region>. Run the following command, replacing <CloudShellResourceGroup> with the Cloud Shell group name.

az group delete --name <CloudShellResourceGroup> --yes

Caution

Deleting resource groups will delete all resources, including resources created outside the scope of this tutorial.

Next steps

This tutorial provides you with a basic idea of how to connect to the Web PubSub service and publish messages to the connected clients.

Check other tutorials to dive further into how to use the service.