Tuesday, 19 May 2015

My Experiments with Truth, oops sorry, SignalR

So what have I been upto these days is a really cool library SignalR

Wanna know more about its where and how abouts? Visit this:


 


 So , after a little researching I got to know you can create two sorts of clients here: JavaScript and .NET clients.

If your mind is like: What Clients?
Dude, you have not gone through the video, eh? :P

Anyways, so Signal R actually facilitates real time conversation, the ones you see in chats like IRC (Internet Relay Chat) . So a message can be broadcasted simultaneously to multiple clients and you can make it possible to gather the responses from the client too.

I have not yet covered the thread safety and async-ness into consideration but overall my code goes somewhat like this:
You can create a broadcast server, that is essentially the hub.

The major files I have are these:
1. Hub Class: Right click your project and select add item>SignalR Hub Class v2

Make sure you are creating a web application in visual studio, prior to doing this otherwise this option may not come.
Also, this way it helps adding all relevant SignalR references to your project.
The hub class has simple code as:

public class BroadcastHub : Hub
  {
      
      public void Send(string input)
      {
          Clients.All.broadcastMessage(input);
      }
 
      public void Receive(string name, string output)
      {
          System.Diagnostics.Debug.WriteLine(name + " has given output:" + output);
      }
 
  }


2. Owin Startup Class: Right click the project name and select add item> OWIN startup class.

While I am still in a process to learn more about OWIN, the most I can tell you is :
"OWIN is a specification that defines an API for framework and servers to cooperation. The point of OWIN is to decouple server and application. For example, ASP.NET Identity uses OWIN security, SignalR self hosting uses OWIN hosting, and etc., the examples all use OWIN, therefore they all need to have a startup class, that is defined in "Startup.cs" file."

So inside your startup.cs owin class you would be having code like:
 
using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
 
[assemblyOwinStartup(typeof(ServerBroadcast.Startup))] namespace ServerBroadcast
{     
public class Startup     
{         
public void Configuration(IAppBuilder app)         
{             
app.MapSignalR();         
}     
}
}

3. Client : I have javascript client so it was basically an html page. I named it FakeClient.
Major methods it uses:
<script type="text/javascript">
        $(function () {
            // Declare a proxy to reference the hub.
            var chat = $.connection.broadcastHub;
            // Create a function that the hub can call to broadcast messages.
            chat.client.broadcastMessage = function (message) {
                // Html encode display name and message.
                var encodedMsg = $('<div />').text(message).html();
                // Add the message to the page.
                $('#discussion').append('<li><strong> ' + document.getElementById('displayname').value + ' received '
                    + '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
            };
            // Get the user name and store it to prepend to messages.
            $('#displayname').val(prompt('Which process are you?'''));
            // Set initial focus to message input box.
            $('#message').focus();
            // Start the connection.
            $.connection.hub.start().done(function () {
                    $('#sendoutput').click(function () {
                  
                    chat.server.receive(document.getElementById('displayname').value, $('#output').val());
                    
                    $('#output').val('').focus();
                });
            });
        });
    </script>

From the code, it is evident that once we get connection from the hub in var chat, we can access the server and client part of it as, chat.server.receive, note that receive method is defined in my hub and chat.client.broadcastMessage , broadcastMessage has been a defined method for signalR client.
 
 
 


4. Broadcaster: Since I wanted to give a face to my hub too so I created one more html page and set hat as the start page.

It has simple code as:

<script type="text/javascript">
       $(function () {
           // Declare a proxy to reference the hub.
           var chat = $.connection.broadcastHub;
                   
           // Set initial focus to message input box.
           $('#message').focus();
           // Start the connection.
           $.connection.hub.start().done(function () {
               $('#sendmessage').click(function () {
 
                   // Call the Send method on the hub.
                   chat.server.send($('#message').val());
 
                   // Clear text box and reset focus for next comment.
                   $('#message').val('').focus();
               });
               $('#addclient').click(function () {
                   window.open('http://localhost:44621/FakeClient.html''_blank');
                   window.focus();
 
 
               });
           });
       });
   </script>
 
 
 
So that's pretty much it and you are done, with signalR implementation.
 
Next we would be covering on how to do the same with .NET clients...
Till then see you!
 
Happy hacking!
 


 

2 comments:

  1. we use https://www.firebase.com/docs/web/api/ and so do most people I guess. Getting all that shit is like reinventing the wheel but its cool to know stuff.

    ReplyDelete
    Replies
    1. Hey Vamsi! Thanks for stopping by.
      I can't really agree with your mistaken notion of reinventing the wheel for both have different targeted needs. Yes, Firebase is a preference for most people working on web and frontend technologies but if you want to create lower level, backend stuff, signalR comes handy.

      Delete

A secret love message ~

Hmm, so the trick of putting up a catchy seasonal title worked out, we got you here! Folks, we will be talking about a really cool tech...