你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
适用于 JavaScript 的 Azure Web PubSub 服务客户端库 - 版本 1.1.1
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 并对其进行身份验证
const { WebPubSubServiceClient } = require("@azure/web-pubsub");
const serviceClient = new WebPubSubServiceClient("<ConnectionString>", "<hubName>");
还可以使用终结点和 AzureKeyCredential
对 WebPubSubServiceClient
进行身份验证:
const { WebPubSubServiceClient, AzureKeyCredential } = require("@azure/web-pubsub");
const key = new AzureKeyCredential("<Key>");
const serviceClient = new WebPubSubServiceClient("<Endpoint>", key, "<hubName>");
或使用 Azure Active Directory 对 进行身份验证WebPubSubServiceClient
- 安装
@azure/identity
依赖项
npm install @azure/identity
- 更新源代码以使用
DefaultAzureCredential
:
const { WebPubSubServiceClient, AzureKeyCredential } = require("@azure/web-pubsub");
const { DefaultAzureCredential } = require("@azure/identity");
const key = new DefaultAzureCredential();
const serviceClient = new WebPubSubServiceClient("<Endpoint>", key, "<hubName>");
关键概念
连接
连接(也称为客户端或客户端连接)表示连接到 Web PubSub 服务的单个 WebSocket 连接。 成功连接后,Web PubSub 服务会向此连接分配唯一的连接 ID。
集线器
中心是客户端连接集的逻辑概念。 通常将一个中心用于一种用途,例如聊天中心或通知中心 。 创建客户端连接后,它会连接到某个中心,并且在其生存期内属于该中心。 不同的应用程序可以使用不同的中心名称共享一个 Azure Web PubSub 服务。
组
组是与中心的连接的子集。 可以随时向组添加客户端连接或者从组中删除客户端连接。 例如,当某个客户端加入聊天室,或某个客户端离开聊天室,此类聊天室可以看成是一个组。 一个客户端可以加入多个组,一个组可以包含多个客户端。
用户
与 Web PubSub 的连接可以属于一个用户。 用户可能具有多个连接,例如当单个用户跨多个设备或多个浏览器选项卡进行连接时。
Message
客户端连接后,可以通过 WebSocket 连接将消息发送到上游应用程序或是从上游应用程序接收消息。
示例
获取客户端的访问令牌以启动 WebSocket 连接
const { WebPubSubServiceClient } = require("@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" ] });
// return the token to the WebSocket client
将消息广播到中心内的所有连接
const { WebPubSubServiceClient } = require("@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 筛选器语法。
const { WebPubSubServiceClient, odata } = require("@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)`
});
将消息发送到某个组内的所有连接
const { WebPubSubServiceClient } = require("@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);
将消息发送到某个用户的所有连接
const { WebPubSubServiceClient } = require("@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);
检查该组是否具有任何连接
const { WebPubSubServiceClient } = require("@azure/web-pubsub");
const WebSocket = require("ws");
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 响应
const { WebPubSubServiceClient } = require("@azure/web-pubsub");
function onResponse(rawResponse) {
console.log(rawResponse);
}
const serviceClient = new WebPubSubServiceClient("<ConnectionString>", "<hubName>");
await serviceClient.sendToAll({ message: "Hello world!" }, { onResponse });
疑难解答
启用日志
使用此库时,可设置以下环境变量来获取调试日志。
- 从 SignalR 客户端库获取调试日志
export AZURE_LOG_LEVEL=verbose
有关如何启用日志的更详细说明,请查看 @azure/logger 包文档。
实时跟踪
在 Web PubSub 服务门户中使用“实时跟踪”可查看实时流量。
后续步骤
请查看 示例 目录,获取有关如何使用此库的详细示例。
贡献
若要为此库做出贡献,请阅读贡献指南,详细了解如何生成和测试代码。
相关项目
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈