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

适用于 JavaScript 的 Azure Web PubSub 服务客户端库 - 版本 1.1.4

Azure Web PubSub 服务 是一项 Azure 托管服务,可帮助开发人员轻松构建具有实时功能和发布-订阅模式的 Web 应用程序。 需要服务器和客户端之间或客户端之间的实时发布-订阅消息传送的任何方案都可以使用 Azure Web PubSub 服务。 通常需要从服务器轮询或提交 HTTP 请求的传统实时功能也可以使用 Azure Web PubSub 服务。

可以在应用服务器端使用此库来管理 WebSocket 客户端连接,如下图所示:

溢出

  • 将消息发送到中心和组。
  • 向特定用户和连接发送消息。
  • 将用户和连接组织到组中。
  • 关闭连接
  • 授予、撤销和检查现有连接的权限

有关此处使用的术语的详细信息,请参阅 关键概念 部分。

源代码 | 包(NPM) | API 参考文档 | 产品文档 | 示例

开始

当前支持的环境

先决条件

  • Azure 订阅
  • 现有的 Azure Web PubSub 服务实例。

1.安装 @azure/web-pubsub

npm install @azure/web-pubsub

2.创建并验证 WebPubSubServiceClient

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

const serviceClient = new WebPubSubServiceClient("<ConnectionString>", "<hubName>");

还可以使用终结点和 AzureKeyCredentialWebPubSubServiceClient 进行身份验证:

import { AzureKeyCredential, WebPubSubServiceClient } from "@azure/web-pubsub";

const key = new AzureKeyCredential("<Key>");
const serviceClient = new WebPubSubServiceClient("<Endpoint>", key, "<hubName>");

或者使用 Azure Active DirectoryWebPubSubServiceClient 进行身份验证

  1. 安装 @azure/identity 依赖项
npm install @azure/identity
  1. 更新源代码以使用 DefaultAzureCredential
import { DefaultAzureCredential } from "@azure/identity";
import { WebPubSubServiceClient } from "@azure/web-pubsub";

const key = new DefaultAzureCredential();
const serviceClient = new WebPubSubServiceClient("<Endpoint>", key, "<hubName>");

关键概念

连接

连接(也称为客户端或客户端连接)表示连接到 Web PubSub 服务的单个 WebSocket 连接。 成功连接后,Web PubSub 服务会将唯一的连接 ID 分配给此连接。

枢纽

中心是一组客户端连接的逻辑概念。 通常,将一个中心用于一个目的,例如聊天中心或通知中心。 创建客户端连接时,它会连接到中心,并在其生存期内,它属于该中心。 不同的应用程序可以使用不同的中心名称共享一个 Azure Web PubSub 服务。

组是与中心的连接子集。 你可以向组添加客户端连接,或者随时从组中删除客户端连接。 例如,当客户端加入聊天室或客户端离开聊天室时,可以将此聊天室视为组。 客户端可以加入多个组,一个组可以包含多个客户端。

用户

与 Web PubSub 的连接可以属于一个用户。 用户可能有多个连接,例如,当单个用户跨多个设备或多个浏览器选项卡进行连接时。

消息

当客户端连接时,它可以通过 WebSocket 连接将消息发送到上游应用程序,或从上游应用程序接收消息。

例子

获取客户端启动 WebSocket 连接的访问令牌

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

const serviceClient = new WebPubSubServiceClient("<ConnectionString>", "<hubName>");

// Get the access token for the WebSocket client connection to use
let token = await serviceClient.getClientAccessToken();

// Or get the access token and assign the client a userId
token = await serviceClient.getClientAccessToken({ userId: "user1" });

// Or get the access token that the client will join group GroupA when it connects using the access token
token = await serviceClient.getClientAccessToken({ userId: "user1", groups: ["GroupA"] });

将消息广播到中心中的所有连接

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

const serviceClient = new WebPubSubServiceClient("<ConnectionString>", "<hubName>");

// Send a JSON message
await serviceClient.sendToAll({ message: "Hello world!" });

// Send a plain text message
await serviceClient.sendToAll("Hi there!", { contentType: "text/plain" });

// Send a binary message
const payload = new Uint8Array(10);
await serviceClient.sendToAll(payload.buffer);

使用 OData 筛选器语法将消息发送到中心中的所有连接

有关 filter 语法的详细信息,请参阅 Azure Web PubSub OData 筛选器语法。

import { WebPubSubServiceClient, odata } from "@azure/web-pubsub";

const serviceClient = new WebPubSubServiceClient("<ConnectionString>", "<hubName>");

// Send a JSON message to anonymous connections
await serviceClient.sendToAll({ message: "Hello world!" }, { filter: "userId eq null" });

// Send a text message to connections in groupA but not in groupB
const groupA = "groupA";
const groupB = "groupB";
await serviceClient.sendToAll("Hello world!", {
  contentType: "text/plain",
  // use plain text "'groupA' in groups and not('groupB' in groups)"
  // or use the odata helper method
  filter: odata`${groupA} in groups and not(${groupB} in groups)`,
});

将消息发送到组中的所有连接

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

const serviceClient = new WebPubSubServiceClient("<ConnectionString>", "<hubName>");

const groupClient = serviceClient.group("<groupName>");

// Add user to the group
await groupClient.addUser("user1");

// Send a JSON message
await groupClient.sendToAll({ message: "Hello world!" });

// Send a plain text message
await groupClient.sendToAll("Hi there!", { contentType: "text/plain" });

// Send a binary message
const payload = new Uint8Array(10);
await groupClient.sendToAll(payload.buffer);

将消息发送到用户的所有连接

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

const serviceClient = new WebPubSubServiceClient("<ConnectionString>", "<hubName>");

// Send a JSON message
await serviceClient.sendToUser("user1", { message: "Hello world!" });

// Send a plain text message
await serviceClient.sendToUser("user1", "Hi there!", { contentType: "text/plain" });

// Send a binary message
const payload = new Uint8Array(10);
await serviceClient.sendToUser("user1", payload.buffer);

检查组是否具有任何连接

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

const serviceClient = new WebPubSubServiceClient("<ConnectionString>", "<hubName>");

const groupClient = serviceClient.group("<groupName>");

// close all the connections in the group
await groupClient.closeAllConnections({ reason: "<closeReason>" });

// check if the group has any connections
const hasConnections = await serviceClient.groupExists("<groupName>");

访问操作的原始 HTTP 响应

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

const serviceClient = new WebPubSubServiceClient("<ConnectionString>", "<hubName>");

function onResponse(rawResponse) {
  console.log(rawResponse);
}

await serviceClient.sendToAll({ message: "Hello world!" }, { onResponse });

故障 排除

启用日志

启用日志记录可能有助于发现有关故障的有用信息。 若要查看 HTTP 请求和响应的日志,请将 AZURE_LOG_LEVEL 环境变量设置为 info

export AZURE_LOG_LEVEL=verbose

或者,可以通过在 setLogLevel中调用 @azure/logger 在运行时启用日志记录:

import { setLogLevel } from "@azure/logger";

setLogLevel("info");

有关如何启用日志的更详细说明,可以查看 @azure/记录器包文档

实时跟踪

使用 Web PubSub 服务门户中 实时跟踪 查看实时流量。

后续步骤

有关如何使用此库的详细示例,请查看 示例 目录。

贡献

若要参与此库,请阅读 贡献指南 了解有关如何生成和测试代码的详细信息。