news 2026/6/24 5:38:23

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

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
实时消息传递_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.
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/24 5:36:56

2026年全球社交APP格局大洗牌!这20款APP,你手机里装了几个?

即时通讯赛道杀出一匹黑马&#xff0c;CQCQ强势跻身前三 全球热门社交APP最新排名&#xff0c;这三款霸榜了 移动互联网发展到今天&#xff0c;各大APP早已深度渗透进我们生活的方方面面。无论是想找人聊聊天、刷刷视频解解闷&#xff0c;还是网购淘点好物、远程办公开个会&…

作者头像 李华
网站建设 2026/6/24 5:25:36

一篇文章看懂SSH,TMUX,SCP的原理及使用

SSH / Tmux / SCP 全链路详解&#xff08;服务器内部视角&#xff09; 一、SSH 登录&#xff1a;远程服务器内部发生了什么&#xff1f; 1️⃣ 常驻监听 远程服务器启动后&#xff0c;系统中常驻一个 sshd 主进程&#xff1a; socket(AF_INET, SOCK_STREAM, 0); // 创建 TC…

作者头像 李华
网站建设 2026/6/24 5:22:50

【测试方案_MDIO】快速掌握以太网PHY MDIO测试

目录 1. MDIO概述 2. MDIO工作原理 2.1. MDIO引脚定义 2.2. MDIO协议 2.2.1. MDIO读写区分 2.2.2. MDIO帧结构 2.2.2.1. Clause-22帧结构 2.2.2.2. Clause-45帧结构 2.2.3. MDIO读写时序 2.2.3.1. 写操作时序(WRITE OP=01) 2.2.3.2. 读操作时序(READ OP=10) 2.2.…

作者头像 李华
网站建设 2026/6/24 5:21:27

Web渗透测试实战:SQL注入漏洞从入门到深度防御

# Web渗透测试实战&#xff1a;SQL注入漏洞从入门到深度防御## 1 SQL注入攻击概述SQL注入&#xff08;SQL Injection&#xff09;是Web安全领域最经典的漏洞之一&#xff0c;连续多年位列OWASP Top 10高危漏洞。攻击者通过构造恶意SQL语句&#xff0c;插入应用程序的输入参数&a…

作者头像 李华
网站建设 2026/6/24 5:20:32

SSH MCP Server 详解:让 AI 安全地“握紧”你的服务器

一、项目概述 ssh-mcp-server 是一个基于 SSH 的 Model Context Protocol (MCP) 服务端实现&#xff0c;由开发者 classfang&#xff08;方俊杰&#xff09;开源维护。它充当了 AI 助手与远程服务器之间的安全桥梁&#xff0c;让支持 MCP 协议的客户端&#xff08;如 Claude C…

作者头像 李华