2 September 2014

SignalR - Real Time Communication

Hi All,

Today lets talk about "SignalR", I hope You might have heard about it.  But How to use it you might face some problem.
SignalR is used for real time communication, eg like - social networking site for notification, in your mail inbox for new mail arriving, real time chat application, group chatting forums and other.  Real time communication make sense and we know what does it mean.

When we try to implement real time relationship, the first way came in our mind it polling.. Long-polling or short-polling.. But what about if I say we have one more efficient method then polling?  Oh you got it? is that Web-Socket??  Yes it is.. but if you are going to use Web-Socket or any other HTML5 elements you have to make it sure you are going to support few old browsers as well which doesn't support HTML5 elements.

Now you  might think about long-polling with Web socket?  web-socket for new browser and polling for old browser? Right?

Yes that the way to support the old and new browser. But you have to code for polling and web-socket, then check the browser support, then call the supported coding snippet.  But I am saying no need to code for all SignalR here to do all this.  SignalR is enough intelligent to figure out what to use and how to use.  No need to code for polling and web-socket.

SignalR check the client and Server both, if both support the Web-Socket it goes for web-socket else efficient polling.  The best part is you no need to worry about it and coding part, it takes care for that. :)  Lets see for example and dependencies..


  • JQuery > 1.6 
  • SignalR  JS file
  • SignalR dll
  • Owin dll
  • Newtonsoft.Json dll


but again no worry, follow the below steps one by one - (Download Sample from here)

  • Open your Visual Studio and Create new blank Web Project.
  • Go to TOOLS >  NuGet Package Manager  >  Package Manager Console.  Type the following command on console and hit the  <Enter>, it will process and install and add the reference to your project..
    install-package Microsoft.AspNet.SignalR
  • install this package, it will automatically download all the dependencies and required dll all jquery files.
  • Right click project and add one class called as "Startup.cs"(name should be same) and paste the following code.
  • using Microsoft.Owin;
    using Owin;
    
    [assembly: OwinStartup(typeof(SignalR_For_Upload.Startup))]
    namespace SignalR_For_Upload
    {    
      public class Startup
      {
        public void Configuration(IAppBuilder app)
        {
           app.MapSignalR();
        }
      }
    }
    
    
  • Now create another class file and named it as "MyHub.cs", and paste the below code
  • using Microsoft.AspNet.SignalR;
    using Microsoft.AspNet.SignalR.Hubs;
    
    namespace SignalR_For_Upload
    {
      [HubName("newNameOfHub")]
      public class MyHub : Hub
      {
        public void SendMsg(string message)
        {
          Clients.All.ReceiveMsg(message);
        }
      }
    }
    
    
  • So the above is the Hub which keeps track of all the client and send the message to them using the statement stated above. 
  • Clients.All.ReceiveMsg(message);
    here 'Client.All' mean all the clients while 'ReceiveMsg(message)' is the dynamic expression which can be considered as event name for client 
    
  • Thats all now no more coding .. :) just need to bind up this event from client using javascript snippet. let have a look at that part as well.
  • Create your "Default.aspx" page and replace the "body" section with the following code(You can take the plain html page as well :) no worries).
  • <body>
      <input type="text" id="msg" value=" " />
      <input type="button" id="send" value="send" />
      <ul id="message">
      </ul>
        
      <script src="Scripts/jquery-1.6.4.min.js"></script>
      <script src="Scripts/jquery.signalR-2.1.1.min.js"></script>    
      <script src='<%: ResolveClientUrl("~/signalr/hubs") %>'></script>
      <script>        
        $(function () {
            
           var con = $.hubConnection();
           var hub = con.createHubProxy('newNameOfHub');
            
           hub.on('ReceiveMsg', function (message) {
              $('#message').append('<li>' + message + '</li>');
           });
    
           con.start().done(function () {
              $('#send').click(function () {
                 hub.invoke('sendMsg', $('#msg').val());                    
              });
           });
    
        });
      </script>
    </body>
    
  • So thats it.. just save the page. and run this in two browser and check they are communication in real time.  :)  Download Sample


Happy Code Sharing.. :)

No comments:

Post a Comment