当前位置: 首页 > news >正文

实时消息传递_azure-messaging-webpubsubservice-py

以下为本文档的中文说明

azure-messaging-webpubsubservice-py 是 Azure Web PubSub 服务的 Python SDK 技能,专注于实时消息传递和 WebSocket 连接管理。Azure Web PubSub 是微软 Azure 提供的一项托管服务,支持大规模 WebSocket 连接和发布/订阅消息模式。该技能指导开发者如何正确使用这个 SDK 构建实时应用。核心内容包括:服务端 SDK(azure-messaging-webpubsubservice)用于服务端操作,客户端 SDK(azure-messaging-webpubsubclient)用于 Python WebSocket 客户端。环境配置方面需要设置连接字符串或 Entra ID 认证。服务端功能涵盖:客户端认证与授权——通过 WebPubSubServiceClient 生成客户端访问令牌或获取客户端证书;消息收发——向指定用户、组或所有客户端广播消息;连接管理——管理 WebSocket 连接的生命周期。使用场景包括:实时聊天应用、协作编辑工具、实时数据仪表板、在线游戏、直播互动、物联网设备实时通信等需要低延迟双向通信的应用。核心原则是“托管服务简化实时通信”,通过 Azure 的托管基础设施,开发者无需自己搭建和维护 WebSocket 服务器即可实现大规模实时消息推送。


Azure Web PubSub Service SDK for Python

Real-time messaging with WebSocket connections at scale.

Installation

# Service SDK (server-side)pipinstallazure-messaging-webpubsubservice# Client SDK (for Python WebSocket clients)pipinstallazure-messaging-webpubsubclient

Environment Variables

AZURE_WEBPUBSUB_CONNECTION_STRING=Endpoint=https://<name>.webpubsub.azure.com;AccessKey=...AZURE_WEBPUBSUB_HUB=my-hub

Service Client (Server-Side)

Authentication

fromazure.messaging.webpubsubserviceimportWebPubSubServiceClient# Connection stringclient=WebPubSubServiceClient.from_connection_string(connection_string=os.environ["AZURE_WEBPUBSUB_CONNECTION_STRING"],hub="my-hub")# Entra IDfromazure.identityimportDefaultAzureCredential client=WebPubSubServiceClient(endpoint="https://<name>.webpubsub.azure.com",hub="my-hub",credential=DefaultAzureCredential())

Generate Client Access Token

# Token for anonymous usertoken=client.get_client_access_token()print(f"URL:{token['url']}")# Token with user IDtoken=client.get_client_access_token(user_id="user123",roles=["webpubsub.sendToGroup","webpubsub.joinLeaveGroup"])# Token with groupstoken=client.get_client_access_token(user_id="user123",groups=["group1","group2"])

Send to All Clients

# Send textclient.send_to_all(message="Hello everyone!",content_type="text/plain")# Send JSONclient.send_to_all(message={"type":"notification","data":"Hello"},content_type="application/json")

Send to User

client.send_to_user(user_id="user123",message="Hello user!",content_type="text/plain")

Send to Group

client.send_to_group(group="my-group",message="Hello group!",content_type="text/plain")

Send to Connection

client.send_to_connection(connection_id="abc123",message="Hello connection!",content_type="text/plain")

Group Management

# Add user to groupclient.add_user_to_group(group="my-group",user_id="user123")# Remove user from groupclient.remove_user_from_group(group="my-group",user_id="user123")# Add connection to groupclient.add_connection_to_group(group="my-group",connection_id="abc123")# Remove connection from groupclient.remove_connection_from_group(group="my-group",connection_id="abc123")

Connection Management

# Check if connection existsexists=client.connection_exists(connection_id="abc123")# Check if user has connectionsexists=client.user_exists(user_id="user123")# Check if group has connectionsexists=client.group_exists(group="my-group")# Close connectionclient.close_connection(connection_id="abc123",reason="Session ended")# Close all connections for userclient.close_all_connections(user_id="user123")

Grant/Revoke Permissions

fromazure.messaging.webpubsubserviceimportWebPubSubServiceClient# Grant permissionclient.grant_permission(permission="joinLeaveGroup",connection_id="abc123",target_name="my-group")# Revoke permissionclient.revoke_permission(permission="joinLeaveGroup",connection_id="abc123",target_name="my-group")# Check permissionhas_permission=client.check_permission(permission="joinLeaveGroup",connection_id="abc123",target_name="my-group")

Client SDK (Python WebSocket Client)

fromazure.messaging.webpubsubclientimportWebPubSubClient client=WebPubSubClient(credential=token["url\ ioimportWebPubSubServiceClientfromazure.identity.aioimportDefaultAzureCredentialasyncdefbroadcast():credential=DefaultAzureCredential()client=WebPubSubServiceClient(endpoint="https://<name>.webpubsub.azure.com",hub="my-hub",credential=credential)awaitclient.send_to_all("Hello async!",content_type="text/plain")awaitclient.close()awaitcredential.close()

Client Operations

OperationDescription
get_client_access_tokenGenerate WebSocket connection URL
send_to_allBroadcast to all connections
send_to_userSend to specific user
send_to_groupSend to group members
send_to_connectionSend to specific connection
add_user_to_groupAdd user to group
remove_user_from_groupRemove user from group
close_connectionDisconnect client
connection_existsCheck connection status

Best Practices

  1. Use rolesto limit client permissions
  2. Use groupsfor targeted messaging
  3. Generate short-lived tokensfor security
  4. Use user IDsto send to users across connections
  5. Handle reconnectionin client applications
  6. Use JSONcontent type for structured data
  7. Close connectionsgracefully with reasons

When to Use

This skill is applicable to execute the workflow or actions described in the overview.

Limitations

  • Use this skill only when the task clearly matches the scope described above.
  • Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
  • Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.
http://www.jsqmd.com/news/1070994/

相关文章:

  • Lexical富文本编辑器图片处理全攻略:从拖拽上传到智能裁剪的完整方案
  • ORC屏幕图片文字提取-聊天截图文字提取-截图文字识别-视频文字提取,免费用先
  • imx6ull 开发板,SD卡启动,给EMMC分区,烧系统。
  • C语言 基于分治法的快速排序算法(Quick Sort)
  • VoxCPM2语音合成终极指南:无需分词器的30种语言语音生成与高保真克隆技术
  • 【模块实现 03】ImGui 游戏内菜单:DX12 渲染路径的完整落地
  • React Native CarPlay 发布指南:App Store审核与CarPlay权限申请完整流程
  • 杰理可视化SDK开发-杰理SDK代码区域说明
  • 【AI应用实战-WorkBuddy】效率翻倍:我的 WorkBuddy 工作流分享(十八)
  • DiskGenius:机械硬盘坏了怎么修复?机械硬盘有坏道,记录使用DiskGenius修复全过程
  • 计算机毕业设计之基于jsp“明丽书屋”图书管理系统
  • 事件中心客户端_azure-eventhub-rust
  • 呆啵宠物DyberPet:让二次元角色活在你的桌面,打造专属数字伙伴的终极指南
  • 项目实训个人9--api适配
  • 27家投标,21家满分并列第一!
  • Softer-NMS 深度技术解析:从定位不准确性到精准边框的后处理革命
  • 【聊天机器人项目】7.结合Ollama,Streamlit实现聊天机器人
  • 分布式事务的几种实现方式
  • 如何用不到百元成本打造你的AI语音交互机器人?ESP32开源项目实战指南
  • Pandora与CVE漏洞分析:Kaspersky CVE-2023-23349等安全漏洞实战利用指南 [特殊字符]
  • Workflow-Orchestration 与 Durable Execution
  • linux系统编程(一):pthread常用函数
  • 大模型幻觉治理:2026前沿技术与实战指南
  • 【万字精讲】计算机网络高频填空简答18题:从死记硬背到体系化精通(原题+深度解析+避坑指南)
  • 别再找 Prompt 模板了:提示词的本质,是你和 AI 的任务契约
  • office 2021 下载安装激活
  • 建筑石材选型的数据分析:用pandas对比8类石材性能
  • 第40章:移动端中的AI编程——Flutter/React Native/Kotlin
  • 企业客户获取软件三个月功能使用分析:实际价值与局限性评估
  • 鸿蒙系统的状态和事件