Lately I’ve been reading a bit about SignalR and thinking of the different possibilities. The “hello world” of Real-Time applications, seems to be a chat, there we go:


SignalR basics

The main idea behind SignalR is a proxy that abstracts websockets (or other fallback technologies if websockets are not available) for the developer. But, what does it mean? We want bi-directional client-server communication. In this example I’m using a web client, so I have:

  1. Html website (some javascript + jQuery functions to call the server and I’m including a dinamyc generated js that is the signalR proxy.
  2. .NET Server, it’s just a C# class (Hub) with some functions.

The advantage that we get using SignalR is that from my JS I can call functions from the server –> Then the server can call a method from implemented in JS in the client, not only the client that initially sent the message, but all the open connections.

This diagram shows how using the Hub Proxy (dynamic js in our sample) and the Server Hub we can have a client-server bi-directional communication.


Main code snippets:

Client website:

Html markup: Textfield + Submit button, div to display the messages.

“broadcastMessage” is the client function that can be called from the server when there’s a new message. It’s adding the new chat message to the div.

Server Hub:

This is only the basics, from the server we can group our connections, so we can call the caller, all clients, or a group of clients. This doesn’t have to be triggered always from the client. Remember that it’s a web socket (bi-directional communication) we could have a widget displaying the CPU usage of the server for example.

Is it scalable?

Yes. A single server has a limit on the number of open connections that can hold (a medium Azure / AWS instance can cope with ~20k concurrent connections). If you’re a web developer, you are aware that when using Server Sessions, you also have “problems” scaling horizontally. You need to use a database to store the session data so it can be shared with the web servers, or use Memcached / Redis. The same solution is what we have with SignalR, we can use SQL Server to hold the connections reference, Azure Bus or Redis is also supported.

The source code for this chat is freely available in GitHub.