Twaddle Application Using SignalR

Introduction 

 
Nowadays, chat applications have become pretty common. But still, the idea of how a client gets the message from the server without asking for it or in other words, without any event being fired, is remarkable. Such applications are known as real-time applications because they are responsible for live data exchange as used in multiplayer games, social media, or news forecasts. In real-time applications, the server pushes the message to connected clients instantly it becomes available to all connected clients. So, in this article, we will build a real-time chatting/twaddling application using SignalR. SignalR uses simple Web APIs to connect a server Hub to all of its clients basically, by creating server-to-client RPC (Remote Procedure Calls) that calls JavaScript methods in client browsers from the server and vice-versa.
 
Let's start building a twaddling application which would allow the user to share messages to all users as well as to individual users privately. Firstly, we start by creating a new web application project with MVC template in your visual studio. Then, you need to add the Microsoft.AspNet.SignalR NuGet package reference to the newly created project. After adding the reference, we have to register the SignalR Hub APIs by just calling the predefined method MapHubs() of RouteTableCollection at global.asax. But what does registering of hubs mean? It implies creating a route of the hub URLs and maps each to all the hubs in our project. Here is a demo of how API URLs are registered in the global.asax file,
  1. public class MvcApplication : System.Web.HttpApplication  
  2. {  
  3.     protected void Application_Start()  
  4.     {  
  5.         BundleConfig.RegisterBundles(BundleTable.Bundles);  
  6.         AreaRegistration.RegisterAllAreas();  
  7.         RouteTable.Routes.MapHubs();  
  8.         RouteConfig.RegisterRoutes(RouteTable.Routes);  
  9.     }  
  10. }  
Now, we will create our own hub which will communicate with our client-side's javascript by just inheriting Microsoft.AspNet.SignalR.Hub class. This base class provides us with three properties and three virtuals methods, which would help us build our hub, namely,
  • Clients: A collection of all the clients connected to the hub.
  • Groups: A collection of groups of clients, mainly used for managing groups of clients.
  • Context: Stores the details of that client which has called the server method.
  • connected(): Triggered when a client joins the hub for the first time.
  • OnDisconnected() : Triggered when a client leaves a hub.
  • OnReconnected(): Triggered when a client joins the hub for the next time.
By using this properties and method, we create a hub named MasterHub where we will mainly have our broadcasting logics. So, now its time to define the client methods used in MasterHub but before that, we need to create a hub proxy by adding a script reference of ~/signalr/hubs and start that proxy by calling the predefined method $.connection.hub.start(). Here is an example how to create a hub proxy and declare all the client methods,
  1. <script src="~/signalr/hubs"></script>  
  2. <script type="text/javascript">  
  3. $(window).load(function () {  
  4.     let hub = $.connection.masterHub;  
  5.     //define all your client-side methods  
  6.     hub.client.LogIn = function (parameters) {  
  7.     //define the client side logics  
  8.     }  
  9.     //finally start the hub proxy  
  10.     $.connection.hub.start().done(function () {  
  11.         $.fn.TwaddlerLogIn(hub);  
  12.     });  
  13. });  
  14. </script>  
Your application is ready for a run. The first step for the client is to get connected to the hub by entering his name.
 
 
Twaddle Application Using SignalR
  1. public class MasterHub : Hub  
  2. {  
  3.     private static List<Twaddler> Twaddlers = new List<Twaddler>();  
  4.   
  5.     private static List<TwaddleDetails> Twaddles = new List<TwaddleDetails>();  
  6.   
  7.     public void OnConnected(string TwaddlerName)  
  8.     {  
  9.         if (!Twaddlers.Any(x => Equals(x.ConnectionId, Context.ConnectionId)))  
  10.         {  
  11.             var twaddler = new Twaddler()  
  12.             {  
  13.                 Name = TwaddlerName,  
  14.                 ConnectionId = Context.ConnectionId  
  15.             };  
  16.   
  17.             Twaddlers.Add(twaddler);  
  18.             Clients.Caller.LogIn(twaddler, Twaddlers, Twaddles);  
  19.   
  20.             //broadcast the new twaddler to all twaddlers  
  21.             Clients.AllExcept(Context.ConnectionId).TwaddlerLogIn(twaddler);  
  22.         }  
  23.     }  
Then, the client could send a message to all the clients in the hub, globally.
 
Twaddle Application Using SignalR
  1. public void BroadcastTwaddle(TwaddleDetails twaddle)  
  2. {  
  3.     Twaddles.Add(twaddle);  
  4.     //broadcast the new twaddle to all twaddlers  
  5.     Clients.All.BroadcastTwaddle(twaddle);  
  6. }  
The client could also send a private message to any specific hub, privately.
 
Twaddle Application Using SignalR
  1. public void PrivateTwaddle(string reciverId, string message)  
  2. {  
  3.     var reciver = Twaddlers.Find(x => Equals(x.ConnectionId, reciverId));  
  4.     if (reciver == null)  
  5.         return;  
  6.   
  7.     var sender = Twaddlers.Find(x => Equals(x.ConnectionId, Context.ConnectionId));  
  8.     if (sender == null)  
  9.         return;  
  10.   
  11.     var privateTwaddle = new TwaddleDetails()  
  12.     {  
  13.         Twaddler = sender.Name,  
  14.         TwaddleContent = message  
  15.     };  
  16.   
  17.     Clients.Client(reciverId).PrivateTwaddle(sender.ConnectionId, privateTwaddle);  
  18.     Clients.Caller.PrivateTwaddle(reciver.ConnectionId, privateTwaddle);  
  19. }  
And lastly, inform other clients when this client gets disconnected.
 
Twaddle Application Using SignalR
  1. public override Task OnDisconnected()  
  2. {  
  3.     var twaddler = Twaddlers.Find(x => Equals(x.ConnectionId, Context.ConnectionId));  
  4.     if (twaddler != null)  
  5.     {  
  6.         Twaddlers.Remove(twaddler);  
  7.   
  8.         //broadcast the twaddler has loggedout to all twaddlers  
  9.         Clients.All.BoradcastTwaddlerLogOut(twaddler);  
  10.     }  
  11.     return base.OnDisconnected();  
  12. }  

Summary 

 
Finally, you have successfully used SignalR to build your own real-time application which allows users to create private as well as global chat rooms by just writing a few server and client methods. Click here to get to the Twaddler project repository.