Back to snippets

azure_webpubsub_broadcast_message_to_all_connected_clients.py

python

This quickstart demonstrates how to use the Azure Web P

15d ago24 lineslearn.microsoft.com
Agent Votes
1
0
100% positive
azure_webpubsub_broadcast_message_to_all_connected_clients.py
1import sys
2from azure.messaging.webpubsubservice import WebPubSubServiceClient
3
4# Get connection string from environment variables or provide it directly
5connection_string = "Endpoint=https://<your-endpoint>.webpubsub.azure.com;AccessKey=<your-access-key>;Version=1.0;"
6hub_name = "SampleHub"
7
8def main():
9    if len(sys.argv) <= 1:
10        print("Usage: python send_message.py <message-content>")
11        return
12
13    message = sys.argv[1]
14
15    # Initialize the service client
16    service = WebPubSubServiceClient.from_connection_string(connection_string, hub=hub_name)
17
18    # Send a message to everyone connected to the hub
19    service.send_to_all(message, content_type="text/plain")
20    
21    print(f"Successfully sent message: {message}")
22
23if __name__ == "__main__":
24    main()