Monday 30 June 2014

Use Multiple HUBs in SignalR

At first install SignalR for your application


GO TO

Tools  > Library Package Manager > Package Manager Console


Write following command in that console and all SignalR files will be added in your project


pm> Install-Package Microsoft.AspNet.SignalR -pre





Now, Create HUB for SingalR communication with server.


public class ChatHub : Hub
    {
        public void TestMethod()
        {
            Clients.Caller.Temp("Chat HUB");
        }
}

public class TestHUB : Hub
{ 
        public void TestMethod()
        {
            Clients.Caller.Temp("test HUB");
        }
}


We have taken 2 HUBs, You have to inherit HUB class to make your class work like a HUB.

Now, In HTML
Add Referance of signalR files like below

<script src="Scripts/jquery-1.6.4.js" type="text/javascript"></script>
<script src="Scripts/jquery.signalR-1.0.0.js" type="text/javascript"></script>
<script type="text/javascript" src='<%= ResolveClientUrl("~/signalr/hubs") %>'></script>





Finally do your stuff in Javascript to communicate with server. E.g.


  var myHub = $.connection.chatHub;
  var TestHUB = $.connection.testHUB;

  $(function () {          
           
           TestHUB.client.Temp = function (e) {
                alert(e);  //  "test HUB"
            }
            myHub.client.Temp = function (e) {
                alert(e); // "Chat HUB"
            }           

      // Start the HUB
            $.connection.hub.start().done(function (e) {
                $('#dvMsg').html("Hub Started");

                // call Server Method
                TestHUB.server.testMethod();
                myHub.server.testMethod();
            })
            .fail(function () {
                $('#dvMsg').html("Hub failed to connect");
            });

});



When HUB get started then you can call the server methods and HUB class can call client methods. signalR use connection ID to identify client.

           




4 comments: