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

📅 2026/6/24 5:38:35
实时消息传递_azure-messaging-webpubsubservice-py
以下为本文档的中文说明azure-messaging-webpubsubservice-py 是 Azure Web PubSub 服务的 Python SDK 技能专注于实时消息传递和 WebSocket 连接管理。Azure Web PubSub 是微软 Azure 提供的一项托管服务支持大规模 WebSocket 连接和发布/订阅消息模式。该技能指导开发者如何正确使用这个 SDK 构建实时应用。核心内容包括服务端 SDKazure-messaging-webpubsubservice用于服务端操作客户端 SDKazure-messaging-webpubsubclient用于 Python WebSocket 客户端。环境配置方面需要设置连接字符串或 Entra ID 认证。服务端功能涵盖客户端认证与授权——通过 WebPubSubServiceClient 生成客户端访问令牌或获取客户端证书消息收发——向指定用户、组或所有客户端广播消息连接管理——管理 WebSocket 连接的生命周期。使用场景包括实时聊天应用、协作编辑工具、实时数据仪表板、在线游戏、直播互动、物联网设备实时通信等需要低延迟双向通信的应用。核心原则是“托管服务简化实时通信”通过 Azure 的托管基础设施开发者无需自己搭建和维护 WebSocket 服务器即可实现大规模实时消息推送。Azure Web PubSub Service SDK for PythonReal-time messaging with WebSocket connections at scale.Installation# Service SDK (server-side)pipinstallazure-messaging-webpubsubservice# Client SDK (for Python WebSocket clients)pipinstallazure-messaging-webpubsubclientEnvironment VariablesAZURE_WEBPUBSUB_CONNECTION_STRINGEndpointhttps://name.webpubsub.azure.com;AccessKey...AZURE_WEBPUBSUB_HUBmy-hubService Client (Server-Side)Authenticationfromazure.messaging.webpubsubserviceimportWebPubSubServiceClient# Connection stringclientWebPubSubServiceClient.from_connection_string(connection_stringos.environ[AZURE_WEBPUBSUB_CONNECTION_STRING],hubmy-hub)# Entra IDfromazure.identityimportDefaultAzureCredential clientWebPubSubServiceClient(endpointhttps://name.webpubsub.azure.com,hubmy-hub,credentialDefaultAzureCredential())Generate Client Access Token# Token for anonymous usertokenclient.get_client_access_token()print(fURL:{token[url]})# Token with user IDtokenclient.get_client_access_token(user_iduser123,roles[webpubsub.sendToGroup,webpubsub.joinLeaveGroup])# Token with groupstokenclient.get_client_access_token(user_iduser123,groups[group1,group2])Send to All Clients# Send textclient.send_to_all(messageHello everyone!,content_typetext/plain)# Send JSONclient.send_to_all(message{type:notification,data:Hello},content_typeapplication/json)Send to Userclient.send_to_user(user_iduser123,messageHello user!,content_typetext/plain)Send to Groupclient.send_to_group(groupmy-group,messageHello group!,content_typetext/plain)Send to Connectionclient.send_to_connection(connection_idabc123,messageHello connection!,content_typetext/plain)Group Management# Add user to groupclient.add_user_to_group(groupmy-group,user_iduser123)# Remove user from groupclient.remove_user_from_group(groupmy-group,user_iduser123)# Add connection to groupclient.add_connection_to_group(groupmy-group,connection_idabc123)# Remove connection from groupclient.remove_connection_from_group(groupmy-group,connection_idabc123)Connection Management# Check if connection existsexistsclient.connection_exists(connection_idabc123)# Check if user has connectionsexistsclient.user_exists(user_iduser123)# Check if group has connectionsexistsclient.group_exists(groupmy-group)# Close connectionclient.close_connection(connection_idabc123,reasonSession ended)# Close all connections for userclient.close_all_connections(user_iduser123)Grant/Revoke Permissionsfromazure.messaging.webpubsubserviceimportWebPubSubServiceClient# Grant permissionclient.grant_permission(permissionjoinLeaveGroup,connection_idabc123,target_namemy-group)# Revoke permissionclient.revoke_permission(permissionjoinLeaveGroup,connection_idabc123,target_namemy-group)# Check permissionhas_permissionclient.check_permission(permissionjoinLeaveGroup,connection_idabc123,target_namemy-group)Client SDK (Python WebSocket Client)fromazure.messaging.webpubsubclientimportWebPubSubClient clientWebPubSubClient(credentialtoken[url\ ioimportWebPubSubServiceClientfromazure.identity.aioimportDefaultAzureCredentialasyncdefbroadcast():credentialDefaultAzureCredential()clientWebPubSubServiceClient(endpointhttps://name.webpubsub.azure.com,hubmy-hub,credentialcredential)awaitclient.send_to_all(Hello async!,content_typetext/plain)awaitclient.close()awaitcredential.close()Client OperationsOperationDescriptionget_client_access_tokenGenerate WebSocket connection URLsend_to_allBroadcast to all connectionssend_to_userSend to specific usersend_to_groupSend to group memberssend_to_connectionSend to specific connectionadd_user_to_groupAdd user to groupremove_user_from_groupRemove user from groupclose_connectionDisconnect clientconnection_existsCheck connection statusBest PracticesUse rolesto limit client permissionsUse groupsfor targeted messagingGenerate short-lived tokensfor securityUse user IDsto send to users across connectionsHandle reconnectionin client applicationsUse JSONcontent type for structured dataClose connectionsgracefully with reasonsWhen to UseThis skill is applicable to execute the workflow or actions described in the overview.LimitationsUse 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.