从服务器推送消息

熟悉的 HTTP 请求/响应模型设计为易于使用且可缩放。 但是如今,最终用户对 Web 的需求比最初设计时要多得多。 HTTP 协议要求用户启动请求才能接收响应。 但开发人员需要一种方法来将数据从服务器发送到客户端,而无需他们要求;换句话说,他们需要向客户端“推送”数据,比如在拍卖网站上推送产品的最新出价,或者在金融应用程序中推送快速变化的股价。

GIF of application server pushing data to connected client.

本快速入门指南演示了如何

  • 订阅来自应用程序服务器的消息
  • 将数据从应用程序服务器推送所有连接的客户端

先决条件

  • Web PubSub 资源。 如果尚未创建,可以按照以下指导操作:创建 Web PubSub 资源
  • 代码编辑器,如 Visual Studio Code
  • 安装计划使用的语言的依赖项

创建订阅服务器客户端

若要订阅从应用程序服务器推送的消息,客户端(无论是浏览器、移动应用还是 IoT 设备)需要先连接到 Web PubSub 资源,并侦听相应的消息事件。

创建一个名为 subscriber 的项目目录,并安装所需的依赖项

mkdir subscriber
cd subscriber
npm init -y

# The client SDK is available as a module on NPM
npm install @azure/web-pubsub-client

连接到 Web PubSub 资源并为 server-message 事件注册侦听器

客户端使用客户端访问 URL 连接资源并向其进行身份验证。 此 URL 遵循 wss://<service_name>.webpubsub.azure.com/client/hubs/<hub_name>?access_token=<token> 的模式。 客户端可以通过几种方式获取客户端访问 URL。 对于本快速入门,可以从 Azure 门户复制并粘贴 URL,如下图所示。 最佳做法是不要在代码中对客户端访问 URL 进行硬编码。 在生产环境中,我们通常设置应用服务器按需返回此 URL。 生成客户端访问 URL 详细介绍了相关操作。

The diagram shows how to get client access url.

如上图所示,客户端加入名为 myHub1 的中心。

subscriber 项目文件夹中,使用以下代码创建名为 subscribe.js 的文件

import { WebPubSubClient } from "@azure/web-pubsub-client";

// Instantiates the client object
// <client-access-url> is copied from Azure portal mentioned above
const client = new WebPubSubClient("<client-access-url>")

// Registers a handler for the "server-message" event
client.on("server-message", (e) => {
    console.log(`Received message ${e.message.data}`)
});

// Before a client can receive a message, 
// you must invoke start() on the client object.
await client.start();

运行程序

node subscribe.js

现在,此客户端与 Web PubSub 资源建立连接,并准备好接收从应用程序服务器推送的消息。

从应用程序服务器推送消息

现在,你有客户端已连接 Web PubSub 资源,可以使用 Web PubSub 提供的服务器 SDK 随时从应用程序服务器推送消息。

创建一个名为 publisher项目目录,并安装所需的依赖项

mkdir publisher
cd publisher

npm init

# This command installs the server SDK from NPM, 
# which is different from the client SDK you used in subscribe.js
npm install --save @azure/web-pubsub

使用以下代码创建 publish.js 文件

const { WebPubSubServiceClient } = require('@azure/web-pubsub');

// This is the hub name we used on Azure portal when generating the Client Access URL. 
// It ensures this server can push messages to clients in the hub named "myHub1".
const hub = "myHub1";

let server = new WebPubSubServiceClient(process.env.WebPubSubConnectionString, hub);

// By default, the content type is `application/json`. 
// Specify contentType as `text/plain` for this demo.
server.sendToAll(process.argv[2], { contentType: "text/plain" });

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

获取连接字符串

重要

连接字符串包括应用程序访问 Web PubSub 服务所需的授权信息。 连接字符串中的访问密钥类似于服务的根密码。

对于本快速入门指南,我们将从 Azure 门户获取它,如下所示。 A diagram shows how to get client access url.

运行服务器程序

新的命令 shell 中运行以下命令。

# Set the environment variable for your connection string.
export WebPubSubConnectionString="<Put your connection string here>" 

node publish.js "Hello World"

观察客户端收到的消息

GIF of demonstrating an app server pushing data to connected client.

尝试在多个命令 shell 中运行同一个“订阅”程序,以刺激更多客户端。 运行“发布”程序后,应会看到消息实时传递到所有这些客户端。

摘要

本快速入门演示了将消息从应用程序服务器推送到中心内所有连接的客户端是多么容易。 此外,Web PubSub 还允许将消息推送到

  • 中心内的一部分客户端
  • 中心内的特定组
  • 内的一部分客户端

这些 API 支持大量用例,使开发人员能够专注于独特的业务逻辑,同时确保 Web PubSub 提供低延迟(<100 毫秒)高可用性大规模(百万以上的同时连接)

后续步骤

在下一步中,我们将探讨如何使用 Web PubSub 的事件系统,这是生成完整 Web 应用程序所必需的。