你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
适用于 Azure Web PubSub 的 JavaScript SDK
Azure Web PubSub 服务是一项 Azure 托管服务,可帮助开发者轻松构建具有实时功能和发布-订阅模式的 Web 应用程序。 任何需要在服务器和客户端或客户端之间进行实时发布-订阅消息传送的方案都可以使用 Azure Web PubSub 服务。 通常需要从服务器轮询或提交 HTTP 请求的传统实时功能也可以使用 Azure Web PubSub 服务。
为 JavaScript 提供了两个库:服务客户端库和快速中间件。 以下部分包含有关这些库的更多信息。
可以在应用服务器端使用此库来管理 WebSocket 客户端连接,如下图所示:
- 将消息发送到中心和组。
- 将消息发送到特定用户和连接。
- 将用户和连接组织到组中。
- 关闭连接
- 授予、撤销、检查现有连接的权限
源代码 | 包 (NPM) | API 参考文档 | 产品文档 | 示例
- 一个 Azure 订阅。
- 一个现有的 Azure Web PubSub 服务实例。
npm install @azure/web-pubsub
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>"
);
或者使用 Microsoft Entra ID 进行身份验证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>"
);
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>");
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 服务门户中使用“实时跟踪”可查看实时流量。
在建立 WebSocket 连接时,Web PubSub 服务将连接生命周期和消息转换为 CloudEvents 格式的事件。 此库提供一个快速中间件来处理表示 WebSocket 连接的生命周期和消息的事件,如下图所示:
源代码 | 包 (NPM) | API 参考文档 | 产品文档 | 示例
- LTS 版本的 Node.js
- Express 4.x.x 或更高版本
- 一个 Azure 订阅。
- 一个现有的 Azure Web PubSub 终结点。
npm install @azure/web-pubsub-express
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}`
)
);
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.com"],
});
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.com",
"https://<yourAllowedService2>.webpubsub.azure.com",
],
});
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 服务门户中使用“实时跟踪”可查看实时流量。
使用这些资源开始生成自己的应用程序: