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,
    public class MvcApplication : System.Web.HttpApplication  
    {  
        protected void Application_Start()  
        {  
            BundleConfig.RegisterBundles(BundleTable.Bundles);  
            AreaRegistration.RegisterAllAreas();  
            RouteTable.Routes.MapHubs();  
            RouteConfig.RegisterRoutes(RouteTable.Routes);  
        }  
    }  


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,
    <script src="~/signalr/hubs"></script>  
    <script type="text/javascript">  
    $(window).load(function () {  
        let hub = $.connection.masterHub;  
        //define all your client-side methods  
        hub.client.LogIn = function (parameters) {  
        //define the client side logics  
        }  
        //finally start the hub proxy  
        $.connection.hub.start().done(function () {  
            $.fn.TwaddlerLogIn(hub);  
        });  
    });  
    </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.

    public class MasterHub : Hub  
    {  
        private static List<Twaddler> Twaddlers = new List<Twaddler>();  
      
        private static List<TwaddleDetails> Twaddles = new List<TwaddleDetails>();  
      
        public void OnConnected(string TwaddlerName)  
        {  
            if (!Twaddlers.Any(x => Equals(x.ConnectionId, Context.ConnectionId)))  
            {  
                var twaddler = new Twaddler()  
                {  
                    Name = TwaddlerName,  
                    ConnectionId = Context.ConnectionId  
                };  
      
                Twaddlers.Add(twaddler);  
                Clients.Caller.LogIn(twaddler, Twaddlers, Twaddles);  
      
                //broadcast the new twaddler to all twaddlers  
                Clients.AllExcept(Context.ConnectionId).TwaddlerLogIn(twaddler);  
            }  
        }  


Then, the client could send a message to all the clients in the hub, globally.
 

    public void BroadcastTwaddle(TwaddleDetails twaddle)  
    {  
        Twaddles.Add(twaddle);  
        //broadcast the new twaddle to all twaddlers  
        Clients.All.BroadcastTwaddle(twaddle);  
    }  

The client could also send a private message to any specific hub, privately.

    public void PrivateTwaddle(string reciverId, string message)  
    {  
        var reciver = Twaddlers.Find(x => Equals(x.ConnectionId, reciverId));  
        if (reciver == null)  
            return;  
      
        var sender = Twaddlers.Find(x => Equals(x.ConnectionId, Context.ConnectionId));  
        if (sender == null)  
            return;  
      
        var privateTwaddle = new TwaddleDetails()  
        {  
            Twaddler = sender.Name,  
            TwaddleContent = message  
        };  
      
        Clients.Client(reciverId).PrivateTwaddle(sender.ConnectionId, privateTwaddle);  
        Clients.Caller.PrivateTwaddle(reciver.ConnectionId, privateTwaddle);  
    }  


And lastly, inform other clients when this client gets disconnected.



    public override Task OnDisconnected()  
    {  
        var twaddler = Twaddlers.Find(x => Equals(x.ConnectionId, Context.ConnectionId));  
        if (twaddler != null)  
        {  
            Twaddlers.Remove(twaddler);  
      
            //broadcast the twaddler has loggedout to all twaddlers  
            Clients.All.BoradcastTwaddlerLogOut(twaddler);  
        }  
        return base.OnDisconnected();  
    }  


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.

HostForLIFE.eu ASP.NET Core Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.