SignalR Self Hosting With .NET Client

If you have not heard of SignalR, you can think of it as a kind of RPC (remote procedure call), but it is much more advanced than that, where clients may be called by server code, and clients may call server code.

 

Here is what the SignalR web site has to say about itself:

 

ASP.NET SignalR is a new library for ASP.NET developers that makes it incredibly simple to add real-time web functionality to your applications. What is "real-time web" functionality? It’s the ability to have your server-side code push content to the connected clients as it happens, in real-time.

You may have heard of WebSockets, a new HTML5 API that enables bi-directional communication between the browser and server. SignalR will use WebSockets under the covers when it’s available, and gracefully fallback to other techniques and technologies when it isn’t, while your application code stays the same.

SignalR also provides a very simple, high-level API for doing server to client RPC (call JavaScript functions in your clients’ browsers from server-side .NET code) in your ASP.NET application, as well as adding useful hooks for connection management, e.g. connect/disconnect events, grouping connections, authorization.

http://signalr.net/

 

I first wrote about SignalR a while back when I wrote this article with my partner in crime Richard King (Kingo to those that know him) :

http://www.codeproject.com/Articles/324841/EventBroker

At the time SignalR was very novel (even  though that article was only written a year ago) and the only option at that time was a JavaScript client with a ASP .NET hosted Hub. Things have obviously come on leaps and bounds since then. Now there are all sorts of options for using SignalR, here are some options available to you now

  • .NET client (OWIN) client (OWIN was new to me, here is what it means : Open Web Interface for .NET which you can read about more here : OWIN)
  • Azure client
  • Javascript client
  • Redis client

There is also the possibility to self host the Hub which was of particular interest to me for a new side project I wanted to work on. To this end I decided to give the following scenario a go:

 

  • A simple echo hub that would receive messages as strings, which would be reversed and sent to ALL connected clients. Now the clients could be .NET or JavaScript or any of the other supported hubs. For my requirements .NET was all I cared about.
  • A .NET client that would send messages to the server (via the console standard input), and would print out any messages from the server (via the console standard output)

 

The reason I decided to give this a go is that I could not find a single source which had a running demo example of self hosting, and using .NET as a client. So I hope this helps someone.

 

So without further ado, lets look at some code

 

SERVER

The most relevant parts of the server are shown below:

 

Program (main entry point)


public class Program
{
    static void Main(string[] args)
    {
        using (WebApplication.Start<Startup>("http://localhost:8080/"))
        {
            Console.WriteLine("Server running at http://localhost:8080/");
            Console.ReadLine();
        }
    }
}

 

Startup

This is the code that will initiate a connection


public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.MapConnection<RawConnection>("/raw", new ConnectionConfiguration { EnableCrossDomain = true });
        app.MapHubs();
    }
}

 

The Hub

This is what clients will talk to


public class MessageRecievingHub : Hub
{
    public void SendMessage(string message)
    {
        Console.WriteLine(message);
        string it = new string(message.Reverse().ToArray());
        Clients.All.broadCastToClients(it);
    }
}

 

.NET CLIENT

So how about the client, well that is as simple as this:


class Program
{
    static void Main(string[] args)
    {
        var hubConnection = new HubConnection("http://localhost:8080/");
        var serverHub = hubConnection.CreateHubProxy("MessageRecievingHub");
        serverHub.On("broadCastToClients", message => System.Console.WriteLine(message));
        hubConnection.Start().Wait();
        string line = null;
        while ((line = System.Console.ReadLine()) != null)
        {
            // Send a message to the server
            serverHub.Invoke("SendMessage", line).Wait();
        } 

        System.Console.Read();
    }
}

 

As always here is a small demo project : https://dl.dropbox.com/u/2600965/SignalRClientServer.zip

About these ads

9 thoughts on “SignalR Self Hosting With .NET Client

  1. Hi Sacha,

    Thanks for this article. SignalR is a great project, and being able to self-host it opens very interesting possibilities.

    There’s something I don’t understand in your sample project, though; what is the role of the RawConnection class? I put breakpoints in the OnConnected and OnReceived methods, but they’re never hit, and it works exactly the same if you remove the class completely.

    • sachabarber says:

      Thomas I kind of nabbed that 1/2 from one of the SignalR demos. But from my understanding this is required by some client types (such as JavaScript)

  2. Usman says:

    Great information for my similar ongoing project. Can you guide me how can I use/compile this demo in .net framework 3.5? Libs included in demo project is for .net 4
    btw have a Thanks for useful information :)

    • sachabarber says:

      No unfortunately I don’t think I can get it to work with .NET 3.5. In fact I am struggling to get a .NET4.0 version working for myself. Seems once you open it in VS2012 and build things one of the mscorlib.dll things have moved. Nightmare

  3. Dan says:

    Im going to ask, Why this and not a WCF service. I know that SignalR is pretty easy to understand so that is a big bonus but just wanted to get your expert opinion. GReat heads up though!

    • sachabarber says:

      Its shiny its new man. No seriously yeah you could do this with WCF for suer, bit more work though as you need to mantain callback and client list yourself (make it thread safe etc etc), and that would only work with .NET. Where as SignalR hub would work with many different types of client

      • A response I was expecting. Like youR style! SignalR makes COMET or reverse ajax much easier. What I like is the fallback when sockets are not about. For those in the financial sector this is common place as IE6/7 is still rampant.

        Anyway great article. Thanks.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s