Getting Started with self-hosting SignalR using PersistentConnection

SignalR is a great library to help build real-time, single/multi user apps.
Although SignalR is very well documented, I wanted to write a compact sample which demonstrates Client and Server using PersistentConnection.

I have specifically chosen not to use Hub for this demo as there are many samples out there already.

Step 1
Create a console project.

Step 2
Add following nuget packages

Step 3
To create instance of server, pass the url in the Server class’s constructor. Map the connection. Please make sure that you provide “/” at the end in the url.

You then call MapConnection method with a name of the path. This means that now your client connection becomes Url+Path.

Note MapConnection takes a type ‘T’ where T: PersistentConnection. Since PersistentConnection is an abstract class, you typically inherit from PersistentConnection and that becomes the entry point where the client calls arrives. See below a class called ‘MyConnection’

Next you create instance of Client.Connection class, Be careful, there is a connection class in the server as well so you may have to qualify it with Client.Connection here.

Client side events

‘Received’ is called when Server calls you back
‘StateChanged’ is called when the Connection state changes


Step 4
To call server, call “Start” method on the client’s connection object which returns a task so check for the task for any problems before proceeding and then call ‘Send’ method which actually calls server. Once the Send method is executed, ‘OnReceivedAsync’ method of ‘MyConnection’ class is called. Here you can call all the client’s back by executing ‘Connection.Broadcast’ (or just use Connection.Send method calls the client that is waiting for specific signal) method


Source code for MyConnection class


When you run this sample, you should see output like following.


You can download sample from here


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s