Build real-time communication applications with Azure Web PubSub

Azure’s latest service uses WebSockets to deliver a publish-and-subscribe messaging hub.

Microsoft recently released a set of Azure tools, Azure Web PubSub, to help build and run this new generation of applications, taking advantage of the Azure platform-as-a-service approach and its serverless tools to host a publish-and-subscribe service designed to mix one-to-one, one-to-many, and many-to-many communications, all while taking advantage of cloud economics and scalability to deliver a relatively low-cost service.

Azure Web PubSub

Overview

Azure Web PubSub enables you to build real-time messaging web applications using WebSockets and the publish-subscribe pattern. Any platform supporting WebSocket APIs can connect to the service easily, e.g., web pages, mobile applications, edge devices, etc. The service manages the WebSocket connections for you and allows up to 100K concurrent connections. It provides powerful APIs for you to manage these clients and deliver real-time messages.


Introduction

At the heart of the Azure Web PubSub platform is the WebSockets protocol. Supported by all the major browsers and by most code platforms, WebSockets offer a two-way connection between a server and an endpoint, with support for full-duplex communications. Both endpoint and server can send and receive data at the same time, allowing a real-time conversation between applications (and users). It is an important design pattern, as it provides the scaffolding for all types of applications from chat to screen sharing, from document collaboration to gaming, and from real-time Internet of Things sensing to live telemetry feeds.

WebSockets is not best suited for video and audio (though they are supported); for that, you should be thinking about WebRTC and similar protocols. With WebSockets, you are sharing text-based information. That might be updated to a JSON document or a stream of financial data or both sides of a chat. It is a surprisingly useful technique, as much of what we want to do in real-time is not limited to voice and video and does not need to rely on high-bandwidth connections.

Like much of Azure’s application and messaging platform, Azure Web PubSub is a managed service. You do not need to stand up a server; that is all handled by Azure. It manages scaling and reliability for you, so all you need to work on is your code. The scaling aspect of Azure Web PubSub is probably its most important feature. It is designed to work at scale, using globally replicated instances to support millions of connections.

Microsoft announced the preview of the Azure Web PubSub service for building real-time web applications with WebSockets. WebSocket is a standardized protocol that provides full-duplex communication. It is key to building efficient real-time web interactions and is supported by all major browsers as well as web servers. Azure Web PubSub enables you to use WebSockets and the publish-subscribe pattern to easily build real-time web applications, like live monitoring dashboards, cross-platform live chat, real-time location on maps, and more.


Azure Web PubSub is a classic publish-and-subscribe architecture, with the hubs treated as the publisher and clients as subscribers. This simplifies control flows and ensures that your application always remains in control of messaging. Clients connect via WebSockets, with libraries available for most languages and platforms, and initial documentation for JavaScript, C#, Python, and Java.


Building Web PubSub applications

Working with Azure Web PubSub is much like using any other Azure platform service. You start by creating a service instance from the Azure Portal and adding it to a resource group. Then it creates a client access URL which is stored in the portal. This contains an access token that verifies clients against your service.


Prerequisites

  1. .NET Core 2.1 or above
  2. Create an Azure Web PubSub resource

Setup subscriber

In Azure Web PubSub you can connect to the service and subscribe to messages through WebSocket connections. WebSocket is a full-duplex communication channel so the service can push messages to your client in real-time. You can use any API/library that supports WebSocket to do so. For this sample, we use the package Websocket.Client:

STEP 1:  First, create a console app and add the necessary dependencies:

mkdir subsciber
cd subsciber
dotnet new console
dotnet add package Websocket.Client --version 4.3.30
dotnet add package Azure.Messaging.WebPubSub --prerelease
STEP 2:  Update Program.cs to use WebsocketClient to connect 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 above creates a WebSocket connection to connect to a hub in Azure Web PubSub. Hub is a logical unit in Azure Web PubSub where you can publish messages to a group of clients. 

Azure Web PubSub by default doesn’t allow the anonymous connection, so in the code sample, we use 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, you will receive messages through the WebSocket connection. So we use client.MessageReceived.Subscribe(msg => ...)); to listen to incoming messages.

Now save the code above and run it using dotnet run "<connection-string>" <hub-name> (<connection-string> can be found in “Keys” tab in Azure portal, <hub-name> can be any alphabetical string you like), you’ll see a connected message printed out, indicating that you have successfully connected to the service.

Make sure your connection string is enclosed by quotes (“”) in Linux as connection string contains semicolons.

Setup publisher

Now let’s use Azure Web PubSub SDK to publish a message to the service. First, let’s create a publisher project:

mkdir publisher
cd publisher
dotnet new console
dotnet add package Azure.Messaging.WebPubSub --prerelease
using System;
using System;
using System.Linq;
using Azure.Messaging.WebPubSub;

namespace publisher
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length != 3) {
                Console.WriteLine("Usage: publisher   ");
                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);
            serviceClient.SendToAll(message);
        }
    }
}

The sendToAll() call simply sends a message to all connected clients in a hub. Save the code above and run dotnet run "<connection-string>" <hub-name> <message> with the same connection string and hub name you used in subscriber, you’ll see the message printed out in the subscriber.

Since the message is sent to all clients, you can open multiple subscribers simultaneously, and all of them will receive the same message.

The complete code sample of this tutorial can be found here.

Comments

Popular posts from this blog

Cloud Messaging Transformation with Azure Service Bus using Python