Skip to main content

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!
 


 

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

Post a Comment

Popular posts from this blog

Duh - Saves you the trouble to correct your command

Duh.

This is no more an expression for me but a command now. Thanks to the hack I have been doing for past couple of days.

What's it about? Well, here it goes.

How many times it happens that we screw up commands on terminal?
A typo, a syntax mistake or jumbled up arguments. The command doesn't run and then we spend time retyping it ensuring everything is in place this time.
Quite time consuming, eh?




My laziness simply denied me such a behaviour. So I coded up a powershell cmdlet which can do this for me.
Now if I mess up a command, I just have to type 'Duh' and the right command will be displayed on the prompt for you to check and execute (press ENTER).

How Duh operates internally?
Well, guess what. Answer lies in the "tries".
We have a trie and we do closest match using Leveinshtein Distance.
In short, how to figure out how close two strings are?  Find the no of letters you need to remove/insert/replace in order to attain string 2 from string 1.
This is wha…

How would you make an HTML Parser?

Hola folks,

Here we will be walking through how html is being parsed by a widely popular parser: Angle Sharp
You can find it here !
This is just a walkthrough and gives an idea on the breadth of issues  one has to deal with while designing a parser.

Let's sneak peek into what kind of data structures are used and how is the code structured.


It all begins with this line:
var parser = new HtmlParser();
We have folowing variations in constructing the HtmlParser object:

  public HtmlParser()
            : this(Configuration.Default)
        {
        }

        /// <summary>
        /// Creates a new parser with the custom options.
        /// </summary>
        /// <param name="options">The options to use.</param>
        public HtmlParser(HtmlParserOptions options)
            : this(options, Configuration.Default)
        {
        }

        /// <summary>
        /// Creates a new parser with the custom configuration.
        /// </summary&…

What emotions run through your playlist?

Hola !!

Long time. So I was upto creating this application one night , I named: "Playlist Emotions" , "What does the song says" :P , "PlayWithEmotions" and what not, each project of a failed experimentation.

Duh.

The project took way too long. Thanks to the noble idea of making and deploying it as a GWT application and then to improve upon the GUI of the app.
FYI , I tried but done neither of the things above. My Google Console developers trial account  supposedly has some issues with this app, yet to be resolved. So before the entire idea behind the app and the excitement of results it displays fades out , I thought, lemme write a blog post on the same.


So what is this all about?

The idea originated from a candid discussion with my friend on how songs influence our moods and also how our emotions affect the type of songs we listen to.

Being fascinated about knowing what kinds of songs I listen to, I thought of creating an application where I would just e…