Showing posts with label Azure Web PubSub Service. Show all posts
Showing posts with label Azure Web PubSub Service. Show all posts

Wednesday, May 5, 2021

Chat Application using Azure Web PubSub Service (Preview)

Azure Web PubSub service, as its name says, it is based on publish-subscribe pattern and enables us to build real-time web applications. 

Some of the popular examples where we can use this service is, for any chat-based applications, any collaboration application, like white boarding application. We can also use this service for any application which needs instant push notifications. In fact, there are many more example, we can think about. 

The best part is, we can use Azure Web PubSub service on all the platforms which supports WebSocket APIs and it allows up to 100 thousand concurrent connections at any point of time.

Components required to create a basic chat application:

  1. Instance of Azure Web PubSub Service
  2. Publisher application
  3. Subscriber application

To know about how to create and use these components, I’ve created a complete video demonstrating these: 

C# Code for Publisher and Subscriber:

Below is the C# code for the respective classes.

Publisher.cs

  1. var connectionString = "Your_ConnectionString_Here";  
  2. var hub = "Your_Hub_Here";  
  3. var serviceClient = new WebPubSubServiceClient(connectionString, hub);  
  4. while (true)  
  5. {  
  6.       Console.Write("Enter message: ");  
  7.       string message = Console.ReadLine();  
  8.       serviceClient.SendToAll(message);  
  9. }

Subscriber.cs

  1. var connectionString = "Your_ConnectionString_Here";  
  2. var hub = "Your_Hub_Here";  
  3.   
  4. // Either generate the URL or fetch it from server or fetch a temp one from the portal  
  5. var serviceClient = new WebPubSubServiceClient(connectionString, hub);  
  6. var url = serviceClient.GetClientAccessUri();  
  7.   
  8. using (var client = new WebsocketClient(url))  
  9. {  
  10.     client.MessageReceived.Subscribe(msg => Console.WriteLine($"Message received: {msg}"));  
  11.     await client.Start();  
  12.     Console.WriteLine("I'm connected.");  
  13.     Console.Read();  
  14. }  

Hope you enjoyed learning about Azure Web PubSub service.