Tutorial: Create a chat app with Azure Web PubSub service

In Publish and subscribe message tutorial, you've learned the basics of publishing and subscribing messages with Azure Web PubSub. In this tutorial, you'll learn the event system of Azure Web PubSub so use it to build a complete web application with real-time communication functionality.

In this tutorial, you learn how to:

  • Create a Web PubSub service instance
  • Configure event handler settings for Azure Web PubSub
  • Build a real-time chat app

If you don't have an Azure subscription, create an Azure free account before you begin.

Prerequisites

  • This setup requires version 2.22.0 or higher of the Azure CLI. If using Azure Cloud Shell, the latest version is already installed.

Create an Azure Web PubSub instance

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

Create a Web PubSub instance

Run az extension add to install or upgrade the webpubsub extension to the current version.

az extension add --upgrade --name webpubsub

Use the Azure CLI az webpubsub create command to create a Web PubSub in the resource group you've created. The following command creates a Free Web PubSub resource under resource group myResourceGroup in EastUS:

Important

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

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

The output of this command shows properties of the newly created resource. Take note of the two properties listed below:

  • Resource Name: The name you provided to 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 ConnectionString for future use

Important

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 be careful to protect your access keys. Use Azure Key Vault to manage and rotate your keys securely. 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.

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.

Copy the fetched ConnectionString and it will be used later in this tutorial as the value of <connection_string>.

Set up the project

Prerequisites

Create the application

In Azure Web PubSub, there are two roles, server and client. This concept is similar to the server and client roles in a web application. Server is responsible for managing the clients, listen, and respond to client messages, while client's role is to send user's messages to server, and receive messages from server and visualize them to end user.

In this tutorial, we'll build a real-time chat web application. In a real web application, server's responsibility also includes authenticating clients and serving static web pages for the application UI.

We'll use ASP.NET Core 6 to host the web pages and handle incoming requests.

First let's create an empty ASP.NET Core app.

  1. Create web app

    dotnet new web
    dotnet add package Microsoft.Azure.WebPubSub.AspNetCore --version 1.0.0-beta.3
    
  2. Replace the default app.MapGet() in Program.cs with following code snippet.

    if (app.Environment.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    
    app.UseStaticFiles();
    app.UseRouting();
    
    app.UseEndpoints(endpoints =>
    {
    });
    
  3. Also create an HTML file and save it as wwwroot/index.html, we'll use it for the UI of the chat app later.

    <html>
      <body>
        <h1>Azure Web PubSub Chat</h1>
      </body>
    </html>
    

You can test the server by running dotnet run --urls http://localhost:8080 and access http://localhost:8080/index.html in browser.

You may remember in the publish and subscribe message tutorial the subscriber uses an API in Web PubSub SDK to generate an access token from connection string and use it to connect to the service. This is usually not safe in a real world application as connection string has high privilege to do any operation to the service so you don't want to share it with any client. Let's change this access token generation process to a REST API at server side, so client can call this API to request an access token every time it needs to connect, without need to hold the connection string.

  1. Install dependencies.

    dotnet add package Microsoft.Extensions.Azure
    
  2. Add a Sample_ChatApp class to handle hub events. Add DI for the service middleware and service client. Don't forget to replace <connection_string> with the one of your services.

    using Microsoft.Azure.WebPubSub.AspNetCore;
    
    var builder = WebApplication.CreateBuilder(args);
    
    builder.Services.AddWebPubSub(
        o => o.ServiceEndpoint = new ServiceEndpoint("<connection_string>"))
        .AddWebPubSubServiceClient<Sample_ChatApp>();
    
    var app = builder.Build();
    
    if (app.Environment.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    
    app.UseDefaultFiles();
    app.UseStaticFiles();
    app.UseRouting();
    
    app.UseEndpoints(endpoints =>
    {
    });
    
    app.Run();
    
    sealed class Sample_ChatApp : WebPubSubHub
    {
    }
    

AddWebPubSubServiceClient<THub>() is used to inject the service client WebPubSubServiceClient<THub>, with which we can use in negotiation step to generate client connection token and in hub methods to invoke service REST APIs when hub events are triggered.

  1. Add a /negotiate API to the server inside app.UseEndpoints to generate the token.

    app.UseEndpoints(endpoints =>
    {    
      endpoints.MapGet("/negotiate", async  (WebPubSubServiceClient<Sample_ChatApp> serviceClient, HttpContext context) =>
      {
          var id = context.Request.Query["id"];
          if (id.Count != 1)
          {
              context.Response.StatusCode = 400;
              await context.Response.WriteAsync("missing user id");
              return;
          }
          await context.Response.WriteAsync(serviceClient.GetClientAccessUri(userId: id).AbsoluteUri);
      });
    });
    

This token generation code is similar to the one we used in the publish and subscribe message tutorial, except we pass one more argument (userId) when generating the token. User ID can be used to identify the identity of client so when you receive a message you know where the message is coming from.

You can test this API by running dotnet run --urls http://localhost:8080 and accessing http://localhost:8080/negotiate?id=<user-id> and it will give you the full url of the Azure Web PubSub with an access token.

  1. Then update index.html to include the following script to get the token from server and connect to service.

    <html>
      <body>
        <h1>Azure Web PubSub Chat</h1>
      </body>
    
      <script>
        (async function () {
          let id = prompt('Please input your user name');
          let res = await fetch(`/negotiate?id=${id}`);
          let url = await res.text();
          let ws = new WebSocket(url);
          ws.onopen = () => console.log('connected');
        })();
      </script>
    </html>
    

If you are using Chrome, you can test it by opening the home page, input your user name. Press F12 to open the Developer Tools window, switch to Console table and you'll see connected being printed in browser console.

Handle events

In Azure Web PubSub, when there are certain activities happening at client side (for example a client is connected or disconnected), service will send notifications to server so it can react to these events.

Events are delivered to server in the form of Webhook. Webhook is served and exposed by the application server and registered at the Azure Web PubSub service side. The service invokes the webhooks whenever an event happens.

Azure Web PubSub follows CloudEvents to describe the event data.

Here we're using Web PubSub middleware SDK, there is already an implementation to parse and process CloudEvents schema, so we don't need to deal with these details. Instead, we can focus on the inner business logic in the hub methods.

  1. Add event handlers inside UseEndpoints. Specify the endpoint path for the events, let's say /eventhandler. The UseEndpoints should look like follows:

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapGet("/negotiate", async  (WebPubSubServiceClient<Sample_ChatApp> serviceClient, HttpContext context) =>
        {
            var id = context.Request.Query["id"];
            if (id.Count != 1)
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("missing user id");
                return;
            }
            await context.Response.WriteAsync(serviceClient.GetClientAccessUri(userId: id).AbsoluteUri);
        });
    
        endpoints.MapWebPubSubHub<Sample_ChatApp>("/eventhandler/{*path}");
    });
    
  2. Go the Sample_ChatApp we created in previous step. Add a constructor to work with WebPubSubServiceClient<Sample_ChatApp> so we can use to invoke service. And override OnConnectedAsync() method to respond when connected event is triggered.

    sealed class Sample_ChatApp : WebPubSubHub
    {
        private readonly WebPubSubServiceClient<Sample_ChatApp> _serviceClient;
    
        public Sample_ChatApp(WebPubSubServiceClient<Sample_ChatApp> serviceClient)
        {
            _serviceClient = serviceClient;
        }
    
        public override async Task OnConnectedAsync(ConnectedEventRequest request)
        {
            await _serviceClient.SendToAllAsync($"[SYSTEM] {request.ConnectionContext.UserId} joined.");
        }
    }
    

In the above code, we use the service client to broadcast a notification message to all of whom is joined.

Set up the event handler

Expose localhost

Then we need to set the Webhook URL in the service so it can know where to call when there is a new event. But there is a problem that our server is running on localhost so does not have an internet accessible endpoint. There are several tools available on the internet to expose localhost to the internet, for example, ngrok, loophole, or TunnelRelay. Here we use ngrok.

  1. First download ngrok from https://ngrok.com/download, extract the executable to your local folder or your system bin folder.

  2. Start ngrok

    ngrok http 8080
    

ngrok will print a URL (https://<domain-name>.ngrok.io) that can be accessed from internet. In above step we listens the /eventhandler path, so next we'd like the service to send events to https://<domain-name>.ngrok.io/eventhandler.

Set event handler

Then we update the service event handler and set the Webhook URL to https://<domain-name>.ngrok.io/eventhandler. Event handlers can be set from either the portal or the CLI as described in this article, here we set it through CLI.

Use the Azure CLI az webpubsub hub create command to create the event handler settings for the chat hub

Important

Replace <your-unique-resource-name> with the name of your Web PubSub resource created from the previous steps. Replace <domain-name> with the name ngrok printed.

az webpubsub hub create -n "<your-unique-resource-name>" -g "myResourceGroup" --hub-name "Sample_ChatApp" --event-handler url-template="https://<domain-name>.ngrok.io/eventHandler" user-event-pattern="*" system-event="connected"

After the update is completed, open the home page http://localhost:8080/index.html, input your user name, you’ll see the connected message printed in the server console.

Handle Message events

Besides system events like connected or disconnected, client can also send messages through the WebSocket connection and these messages will be delivered to server as a special type of event called message event. We can use this event to receive messages from one client and broadcast them to all clients so they can talk to each other.

Implement the OnMessageReceivedAsync() method in Sample_ChatApp.

  1. Handle message event.

    sealed class Sample_ChatApp : WebPubSubHub
    {
        private readonly WebPubSubServiceClient<Sample_ChatApp> _serviceClient;
    
        public Sample_ChatApp(WebPubSubServiceClient<Sample_ChatApp> serviceClient)
        {
            _serviceClient = serviceClient;
        }
    
        public override async Task OnConnectedAsync(ConnectedEventRequest request)
        {
            await _serviceClient.SendToAllAsync($"[SYSTEM] {request.ConnectionContext.UserId} joined.");
        }
    
        public override async ValueTask<UserEventResponse> OnMessageReceivedAsync(UserEventRequest request, CancellationToken cancellationToken)
        {
            await _serviceClient.SendToAllAsync($"[{request.ConnectionContext.UserId}] {request.Data}");
    
            return request.CreateResponse($"[SYSTEM] ack.");
        }
    }
    

    This event handler uses WebPubSubServiceClient.SendToAllAsync() to broadcast the received message to all clients. You can see in the end we returned UserEventResponse, which contains a message directly to the caller and make the WebHook request success. If you have extra logic to validate and would like to break this call, you can throw an exception here. The middleware will deliver the exception message to service and service will drop current client connection. Do not forget to include the using Microsoft.Azure.WebPubSub.Common; statement at the begining of the Program.cs file.

  2. Update index.html to add the logic to send message from user to server and display received messages in the page.

    <html>
    
    <body>
      <h1>Azure Web PubSub Chat</h1>
      <input id="message" placeholder="Type to chat...">
      <div id="messages"></div>
      <script>
        (async function () {
          let id = prompt('Please input your user name');
          let res = await fetch(`/negotiate?id=${id}`);
          let url = await res.text();
          let ws = new WebSocket(url);
          ws.onopen = () => console.log('connected');
    
          let messages = document.querySelector('#messages');
          ws.onmessage = event => {
            let m = document.createElement('p');
            m.innerText = event.data;
            messages.appendChild(m);
          };
    
          let message = document.querySelector('#message');
          message.addEventListener('keypress', e => {
            if (e.charCode !== 13) return;
            ws.send(message.value);
            message.value = '';
          });
        })();
      </script>
    </body>
    
    </html>
    

    You can see in the above code we use WebSocket.send() to send message and WebSocket.onmessage to listen to message from service.

Now run the server using dotnet run --urls http://localhost:8080 and open multiple browser instances to access http://localhost:8080/index.html, then you can chat with each other.

The complete code sample of this tutorial can be found here, the ASP.NET Core 3.1 version here.

Next steps

This tutorial provides you a basic idea of how the event system works in Azure Web PubSub service.

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