Chat Application Using Azure Web PubSub Service (Preview)

Azure Web PubSub service, as its name says, is based on a publish-subscribe pattern and enables us to build real-time web applications.
 
Some of the popular examples where we can use this service are, for any chat-based applications, and collaboration applications, like whiteboarding applications. We can also use this service for any application which needs instant push notifications. In fact, there are many more examples, we can think about.
 
The best part is, we can use Azure Web PubSub service on all the platforms which support 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. An 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.     Console.Write("Enter message: ");  
  6.     string message = Console.ReadLine();  
  7.     serviceClient.SendToAll(message);  
  8. }  
Subscriber.cs
  1. var connectionString = "Your_ConnectionString_Here";  
  2. var hub = "Your_Hub_Here";  
  3. // Either generate the URL or fetch it from server or fetch a temp one from the portal  
  4. var serviceClient = new WebPubSubServiceClient(connectionString, hub);  
  5. var url = serviceClient.GetClientAccessUri();  
  6. using(var client = new WebsocketClient(url)) {  
  7.     client.MessageReceived.Subscribe(msg => Console.WriteLine($ "Message received: {msg}"));  
  8.     await client.Start();  
  9.     Console.WriteLine("I'm connected.");  
  10.     Console.Read();  
  11. }  
Hope you enjoyed learning about the Azure Web PubSub service.