C#

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

16 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.

    1. 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. 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 🙂

    1. 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. 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!

    1. 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

      1. 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.

  4. Great Sacha !!

    Scenary: WPF, WinForms and Console app Clients

    MSMQ in Server
    Windows Service in Server

    Client send message to MSMQ, and Windows Service read message.

    Windows Service requires notify to Clients (Console app and WinForms client) ?

    Any good patterns about it ? f ull source code sample?

    thx

    1. You would have owin self hosted hub in server, and use .net client signalr proxy in all clients, and then have server hub push notifications to all hub clients.

  5. Thanks a lot.

    I have seen your article http://www.codeproject.com/Articles/324841/EventBroker

    I’m newbie using SignalR and OWIN new for me.

    Any open source code sample that you know about Owin self hosted hub in server using good patterns?

    And .net client signalr proxy using in WinForms or Console application maybe?

    I think, you comment there are several options:

    Server

    Owin self hosted hub
    ASP .NET hosted Hub

    Client

    .NET client (OWIN)
    Azure client
    Javascript client
    Redis client

    Thanks a lot for ideas.

    1. No that codeproject one uses very old SignalR version. To be honest this blog post is all you need it has Sever/client code here. There is nothing else you need

  6. Hello guys anyone give me an Example for using chat Application using SignalR concept in .Net 4.0. I am using vs2010 Ultimate so i tried many times with installing nuget version 1.1.3.

    Anyone help me how to configure and use the coding in signalR for one to one ,&one to many chatting process send me example coding for .Net 4.0 supporting code( soundararajanom@gmail.com)

    Thanks guys

    1. If you are using ASP MVC there are loads of examples. If you want to NOT use ASP MVC, you will have to self host the Signalr hub and use the .ENt client, code would be very simliar to ASP MVC example though, except the host part

Leave a comment