Skip to main content

Continuing with SignalR

Hola amigo!!!

Ella unnav? (How are you? in Telugu :D )

Anyways, so here we continue with the second part of making apps with SignalR, a pretty cool library, for first part refer:

So struggling to figure out how to implement signalR in console apps that with .NET Client, I finally got the way through it.

You need to have two separate projects(preferably):
1. Server 
2. Client

Inside Server:

I have a main class, a startup class and a hub.
Before starting make sure you have added relevant references beforehand.
Right click the project name and select Manage NuGet Packages, install:
signalR .NET client : Microsoft ASP.NET SignalR .NET Client
and  also SelfHosting 

One thing that comes into scens and is the most important is Cross Domain Communication.

Both the server and the client are separate projects now, so the client must be able to identify and connect to the server running in parallel as a separate project. What changes do we need to incorporate with the same?

Here they are:

Majorly the Startup.cs OWIN class gets changed to support cross domain connection.
Refer this for more details on what it is:

So the startup file is changed to:

using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
using Microsoft.Owin.Cors;
using Microsoft.AspNet.SignalR;
namespace BroadcasterConsole
    public class Startup
        public void Configuration(IAppBuilder app)
            app.Map("/signalr", map =>
                var hubConfiguration = new HubConfiguration
                    EnableJSONP = true

CorsOptions.AllowAll  will help your cross domain client to connect to te serevr. Also, please don't miss out the line:  [assemblyOwinStartup(typeof(BroadcasterConsole.Startup))]

Theses changes will make your server been detected and connected by the cross domain clients.

Rest of the server code is more or lesss the same as teh previous code. We need to have a hub class and a main class, I preferred to have them both in same namespace and it goes like this:

namespace BroadcasterConsole
    class Broadcast
        static void Main(string[] args)
            string url = "http://localhost:8088";
                using (WebApp.Start(url))
                  //Have your code here
//Don't forget this line above, this name helps you to connect to the hub from the client side
    public class Broadcaster : Hub
        public override Task OnConnected()
            Console.WriteLine("Hub OnConnected {0}\n", Context.ConnectionId);
            return (base.OnConnected());
 //Define your own hub methods
        public override Task OnReconnected()
            Console.WriteLine("Hub OnReconnected {0}\n", Context.ConnectionId);
            return (base.OnDisconnected(true));

So, let's come back to the client side. I tried to have clients in different languages.

A peek into Javascript Client:

Firstly, include these scripts in this particular order:

   <!--Reference the jQuery library. -->
   <script src="Scripts/jquery-2.1.4.js"></script>
   <!--Reference the SignalR library. -->
   <script src="Scripts/jquery.signalR-2.2.0.js"></script>
   <!--Reference the autogenerated SignalR hub script. -->
   <script src="http://localhost:8088/signalr/hubs" type="text/javascript"></script>

Please see I have hosted my server on 8088 port, change it accordingly, as per the url of your hosted server.

Here goes your main connection code:

<script type="text/javascript">
       $.connection.hub.url = 'http://localhost:8088/signalr';
       var hubProxy = $.connection.broadcaster;
       hubProxy.client.addMessage = function (message) {
           //message is a c# struct Request object.
           // Add the message to the page.
           $('#discussion').append('<li><strong> ' + document.getElementById('displayname').value + ' received request  Name:' + message.Name +  '\n   Program:' + message.Program +  '\n     Input:' + message.Input
               + '</strong>:&nbsp;&nbsp;</li>');
           alert('Now connected, connection ID=' + $;
           $('#displayname').val(prompt('Which process are you?'''));
           $('#sendoutput').click(function () {
               hubProxy.server.getClientOutput({ "Name""JS Client""Result": $('#output').val() });

Its fine if you don't get any of the above code since it would be a bit out of the context you are into. just focus on highlighted lines.

Set the hub url, create a hub Proxy.
Prior to starting teh connection, add the client side methods that the hub can call, for example here we have: addMessage.
Then start the connection by this line:  $.connection.hub.start().done.

You can call server side methods by : hubProxy.server.getClientOutput (//required params)

There we finish with the JavaScript client, we can do the same with clients for different languages:

.NET Client:

//Set connection
           var connection = new HubConnection("http://localhost:8088/");
//Make proxy to hub based on hub name on server
           myHub = connection.CreateHubProxy("Broadcaster");
//Add client side methods

           myHub.On<Request>("addMessage", param =>{
              //Define your method
//Start connection
           connection.Start().ContinueWith(task =>
               if (task.IsFaulted)
                   Console.WriteLine("There was an error opening the connection:{0}",
 //Invoking hub methods

           myHub.Invoke<string>(<Method Name as is>, clientName)

C++ Client:
Here is a detailed guide to do the same with C++.

It is pretty simple to use, in case you have any queries, leave in comments below. So that was all folks, see you in next post! Till then, Happy Hacking! Meanwhile, get your signals across using SignalR :D


Popular posts from this blog

Duh - Saves you the trouble to correct your command


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.


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…