Azure Web PubSub 服务 是一种 Azure 托管服务,可帮助开发人员轻松构建具有实时功能和发布-订阅模式的 Web 应用程序。 需要服务器和客户端之间或客户端之间的实时发布-订阅消息传送的任何方案都可以使用 Azure Web PubSub 服务。 通常需要从服务器轮询或提交 HTTP 请求的传统实时功能也可以使用 Azure Web PubSub 服务。
为 JavaScript 提供两个库:服务客户端库和快速中间件。 以下部分包含有关这些库的详细信息。
- 服务客户端库
- Express 中间件
适用于 JavaScript 的 Azure Web PubSub 服务客户端库
可以在应用服务器端使用此库来管理 WebSocket 客户端连接,如下图所示:
- 将消息发送到中心和组。
- 向特定用户和连接发送消息。
- 将用户和连接分组组织。
- 关闭连接
- 授予、撤销和检查现有连接的权限
入门指南
当前支持的环境
先决条件
- 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>"
);
或者使用 WebPubSubServiceClient 进行身份验证
-
@azure/identity安装依赖项
npm install @azure/identity
- 更新源代码以使用
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/记录器包文档。
实时跟踪
使用 Web PubSub 服务门户中的 实时跟踪 查看实时流量。
适用于 Express 的 Azure Web PubSub CloudEvents 处理程序
当 WebSocket 连接连接时,Web PubSub 服务会将连接生命周期和消息转换为 CloudEvents 格式的事件。 此库提供一个快速中间件来处理表示 WebSocket 连接的生命周期和消息的事件,如下图所示:
源代码 | 包 (NPM) | API 参考文档 | 产品文档 | 样品
入门指南
当前支持的环境
- LTS 版本的 Node.js
- Express 版本 4.x.x 或更高版本
先决条件
- Azure 试用版订阅。
- 现有的 Azure Web PubSub 终结点。
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}`
)
);
Troubleshooting
启用日志
可以使用此库设置以下环境变量来获取调试日志。
- 从 Azure Web PubSub 客户端库获取调试日志
export AZURE_LOG_LEVEL=verbose
有关如何启用日志的更详细说明,请参阅 @azure/记录器包文档。
实时跟踪
使用 Web PubSub 服务门户中的 实时跟踪 查看实时流量。
后续步骤
使用这些资源开始生成自己的应用程序: