你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

教程:使用 WebSocket API 和 Azure Web PubSub 服务 SDK 发布和订阅消息

Azure Web PubSub 服务可帮助你轻松生成实时 Web 消息传递应用程序。 本教程介绍如何使用 WebSocket API 订阅服务,以及如何使用 Web PubSub 服务 SDK 发布消息。

在本教程中,你将了解:

  • 创建 Web PubSub 服务实例
  • 生成完整 URL 以建立 WebSocket 连接
  • 创建 Web PubSub 订阅服务器客户端以使用标准 WebSocket 协议接收消息
  • 创建 Web PubSub 发布服务器客户端以使用 Web PubSub 服务 SDK 发布消息

先决条件

  • Azure 订阅(创建免费帐户)。
  • Bash 命令 shell。 使用本地 shell 或 Azure Cloud Shell 中的 Bash 环境。
  • 如果在本地计算机上运行,请安装 Azure CLI

你可以使用 Windows cmd.exe 命令 shell 而不是 Bash shell 来运行本教程中的命令。

如果在本地计算机上创建项目,则需要安装所用语言的依赖项:

准备环境

用于本地开发的 Azure CLI 设置

按照以下步骤设置 Azure CLI 和项目环境。

  1. 打开命令行界面。

  2. 升级到最新版本的 Azure CLI。

    az upgrade
    
  3. 安装 Web PubSub 的 Azure CLI 扩展。

    az extension add --name webpubsub
    
  4. 登录到 Azure CLI。 按照提示输入你的 Azure 凭据。

    az login
    

创建资源组

资源组是在其中部署和管理 Azure 资源的逻辑容器。 使用 az group create 命令在 eastus 位置创建名为 myResourceGroup 的资源组。

az group create --name myResourceGroup --location EastUS

1. 创建 Azure Web PubSub 实例

创建 Web PubSub 实例

使用 Azure CLI az webpubsub create 命令在已创建的资源组中创建 Web PubSub。 以下命令在 EastUS 的资源组 myResourceGroup 下创建一个免费的 Web PubSub 资源:

每个 Web PubSub 资源必须具有唯一名称。 在以下命令中,将 <your-unique-resource-name> 替换为 Web PubSub 实例的名称。

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

此命令的输出会显示新建的资源的属性。 请记下下面列出的两个属性:

  • 名称:在上面的 --name 参数中提供的 Web PubSub 名称。
  • 主机名:在本例中,主机名为 <your-unique-resource-name>.webpubsub.azure.com/

目前,只有你的 Azure 帐户才有权对这个新资源执行任何操作。

获取连接字符串

重要

连接字符串包括应用程序访问 Azure Web PubSub 服务所需的授权信息。 连接字符串中的访问密钥类似于服务的根密码。 在生产环境中,请始终小心保护访问密钥。 使用 Azure 密钥保管库安全地管理和轮换密钥。 避免将访问密钥分发给其他用户、对其进行硬编码或将其以纯文本形式保存在其他人可以访问的任何位置。 如果你认为访问密钥可能已泄露,请轮换密钥。

使用 Azure CLI az webpubsub key 命令获取服务的 ConnectionString。 将 <your-unique-resource-name> 占位符替换为 Azure Web PubSub 实例的名称。

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

复制主连接字符串以供稍后使用。

创建订阅服务器客户端

客户端使用 JSON Web 令牌 (JWT) 身份验证通过标准 WebSocket 协议连接到 Azure Web PubSub 服务。 服务 SDK 提供帮助程序方法来生成令牌。 在本教程中,订阅者直接根据 ConnectionString 生成令牌。 在真实应用程序中,服务器端应用程序通常会处理身份验证/授权工作流。 若要更好地了解该工作流,请参阅教程生成聊天应用

  1. 首先,为此项目创建一个名为 subscriber 的项目目录,并安装所需的依赖项:

    • Websocket.Client 包是支持 WebSocket 连接的第三方包。 可以使用任何支持 WebSocket 的 API 或库。
    • SDK 包 Azure.Messaging.WebPubSub 可帮助生成 JWT 令牌。
    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. Program.cs 中的代码替换为以下会连接到服务的代码:

    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();
                }
            }
        }
    }
    
    

    该代码创建与 Web PubSub 中某个中心的 WebSocket 连接。 中心是 Web PubSub 中的一个逻辑单元,你可以在其中向一组客户端发布消息。 关键概念包含有关 Web PubSub 中使用的术语的详细解释。

    Web PubSub 服务使用 JSON Web 令牌 (JWT) 身份验证。 示例代码使用 Web PubSub SDK 中的 WebPubSubServiceClient.GetClientAccessUri() 生成服务的 URL,其中包含完整 URL 和有效的访问令牌。

    建立连接后,客户端将通过 WebSocket 连接接收消息。 客户端使用 client.MessageReceived.Subscribe(msg => ...)); 侦听传入的消息。

  3. 若要启动订阅服务器,请运行以下命令,将 <Web-PubSub-connection-string> 替换为之前复制的连接字符串:

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

2. 使用服务 SDK 发布消息

使用 Azure Web PubSub SDK 创建发布服务器,以将消息发布到连接的客户端。 对于此项目,需要打开另一个命令 shell。

  1. 首先,创建一个名为 publisher 的项目目录,并安装所需的依赖项:

    mkdir publisher
    cd publisher
    dotnet new console
    dotnet add package Azure.Messaging.WebPubSub
    
  2. 更新 Program.cs 文件,以使用 WebPubSubServiceClient 类并将消息发送到客户端。

    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);
            }
        }
    }
    
    

    SendToAllAsync() 调用会直接将消息发送到中心内所有已连接的客户端。

  3. 运行以下命令,发送消息。 将 <Web-PubSub-connection-string> 替换为先前复制的连接字符串。

    dotnet run <Web-PubSub-connection-string> "myHub1" "Hello World"
    
  4. 检查订阅服务器的命令 shell,查看该订阅服务器是否收到了消息:

    Message received: Hello World
    

清理

可以删除在本快速入门中创建的资源,只需删除包含这些资源的资源组即可。

az group delete --name myResourceGroup --yes

如果你不打算继续使用 Azure Cloud Shell,可以通过删除包含关联存储帐户的资源组来避免累积成本。 该资源组名为 cloud-shell-storage-<your-region>。 运行以下命令(将其中的 <CloudShellResourceGroup> 替换为 Cloud Shell 组名称)。

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

注意

删除资源组会删除所有资源,包括在本教程范围之外创建的资源。

后续步骤

本教程大致介绍了如何连接到 Web PubSub 服务以及如何将消息发布到连接的客户端。

请查看其他教程,进一步深入了解如何使用该服务。