Compartir a través de

适用于 Azure Web PubSub 的 JavaScript SDK

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

为 JavaScript 提供了两个库:服务客户端库和快速中间件。 以下部分包含有关这些库的更多信息。

适用于 JavaScript 的 Azure Web PubSub 服务客户端库

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

The overflow diagram shows the overflow of using the service client library.

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

源代码 | (NPM) | 产品文档 | 示例

入门

目前支持的环境

先决条件

1. 安装 @azure/web-pubsub

npm install @azure/web-pubsub

2. 创建 WebPubSubServiceClient 并对其进行身份验证

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

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

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

const { WebPubSubServiceClient, AzureKeyCredential } = require("@azure/web-pubsub");

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

或者使用 Microsoft Entra IDWebPubSubServiceClient 进行身份验证

  1. 安装 @azure/identity 依赖项
npm install @azure/identity
  1. 更新源代码以使用 DefaultAzureCredential
const { WebPubSubServiceClient, AzureKeyCredential } = require("@azure/web-pubsub");

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

示例

获取客户端的访问令牌以启动 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" });

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

将消息发送到某个组内的所有连接

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: FullOperationResponse): void {
  console.log(rawResponse);
}
const serviceClient = new WebPubSubServiceClient("<ConnectionString>", "<hubName>");
await serviceClient.sendToAll({ message: "Hello world!" }, { onResponse });

服务客户端故障排除

启用日志

使用此库时,可设置以下环境变量来获取调试日志。

  • 从 Azure Web PubSub 客户端库获取调试日志
export AZURE_LOG_LEVEL=verbose

有关如何启用日志的更详细说明,请查看 @azure/logger 包文档

实时跟踪

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

适用于 Express 的 Azure Web PubSub CloudEvents 处理程序

在建立 WebSocket 连接时,Web PubSub 服务将连接生命周期和消息转换为 CloudEvents 格式的事件。 此库提供一个快速中间件来处理表示 WebSocket 连接的生命周期和消息的事件,如下图所示:

The overflow diagram shows the overflow of using the event handler middleware.

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

入门

目前支持的环境

先决条件

1. 安装 @azure/web-pubsub-express

npm install @azure/web-pubsub-express

2. 创建 WebPubSubEventHandler

const express = require("express");

const { WebPubSubEventHandler } = require("@azure/web-pubsub-express");
const handler = new WebPubSubEventHandler("chat");

const app = express();

app.use(handler.getMiddleware());

app.listen(3000, () =>
  console.log(`Azure WebPubSub Upstream ready at http://localhost:3000${handler.path}`)
);

快速示例

处理 connect 请求并分配 <userId>

const express = require("express");

const { WebPubSubEventHandler } = require("@azure/web-pubsub-express");
const handler = new WebPubSubEventHandler("chat", {
  handleConnect: (req, res) => {
    // auth the connection and set the userId of the connection
    res.success({
      userId: "<userId>"
    });
  },
  allowedEndpoints: ["https://<yourAllowedService>.webpubsub.azure.cn"]
});

const app = express();

app.use(handler.getMiddleware());

app.listen(3000, () =>
  console.log(`Azure WebPubSub Upstream ready at http://localhost:3000${handler.path}`)
);

仅允许指定的终结点

const express = require("express");

const { WebPubSubEventHandler } = require("@azure/web-pubsub-express");
const handler = new WebPubSubEventHandler("chat", {
  allowedEndpoints: [
    "https://<yourAllowedService1>.webpubsub.azure.cn",
    "https://<yourAllowedService2>.webpubsub.azure.cn"
  ]
});

const app = express();

app.use(handler.getMiddleware());

app.listen(3000, () =>
  console.log(`Azure WebPubSub Upstream ready at http://localhost:3000${handler.path}`)
);

设置自定义事件处理程序路径

const express = require("express");

const { WebPubSubEventHandler } = require("@azure/web-pubsub-express");
const handler = new WebPubSubEventHandler("chat", {
  path: "customPath1"
});

const app = express();

app.use(handler.getMiddleware());

app.listen(3000, () =>
  // Azure WebPubSub Upstream ready at http://localhost:3000/customPath1
  console.log(`Azure WebPubSub Upstream ready at http://localhost:3000${handler.path}`)
);

设置并读取连接状态

const express = require("express");

const { WebPubSubEventHandler } = require("@azure/web-pubsub-express");

const handler = new WebPubSubEventHandler("chat", {
  handleConnect(req, res) {
    // You can set the state for the connection, it lasts throughout the lifetime of the connection
    res.setState("calledTime", 1);
    res.success();
  },
  handleUserEvent(req, res) {
    var calledTime = req.context.states.calledTime++;
    console.log(calledTime);
    // You can also set the state here
    res.setState("calledTime", calledTime);
    res.success();
  }
});

const app = express();

app.use(handler.getMiddleware());

app.listen(3000, () =>
  console.log(`Azure WebPubSub Upstream ready at http://localhost:3000${handler.path}`)
);

疑难解答

启用日志

使用此库时,可设置以下环境变量来获取调试日志。

  • 从 Azure Web PubSub 客户端库获取调试日志
export AZURE_LOG_LEVEL=verbose

有关如何启用日志的详细说明,请参阅 @azure/logger package 文档

实时跟踪

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

后续步骤

使用这些资源开始生成自己的应用程序: