Using SignalR with .Net client
After this post, I got an email from my extremely talented colleague
Bnaya Eshet asking if there’s a way to to SignalR with .Net client.
I said “yes” of course so now I want to demonstrate how to do it.
The server side code is the same as in my previous post, this is just
another client example.
Step 1: Create .Net client project:
Add some .Net project, any project type will do, I will demonstrate with
a WPF project works with MVVM. The code samples will be from the
Step 2: Install SignalR .Net client nuget package
On the project you’ve just created, install Microsoft.AspNet.SignalR.Client
package.Make sure that both server project described in previous post has
the same version. If you didn’t, you will get an error of
“incompatible protocol version“ while trying to connect.
Step 3: Create SignalR connection instance
Using the namespace of Microsoft.AspNet.SignalR.Client.Hubs on
Microsoft.AspNet.SignalR.Client assembly (referenced to your project after
NuGet package installation) has a HubConnection class. This class used for
keeping persistent connection.
That’s how you create an instance of this class:
Where the first parameter is the site address, and the second parameter
named useDefaultUrl tells you whether to use the default hubs URL or not.
You should set this parameter according to the way your hubs are registered
on your server.
The default value for that parameter is true, you need this one only if
the hubs aren’t registered at the default URL (thanks
Step 4: Create proxy hub
Another component you can work with is the hub proxy component.
This componentis created by the connection in previous step, using its
CreateHubProxy method. This method returns an IHubProxy interface.
by default it will create a HubProxy class that implements it.
That’s how hub creation looks like:
Step 5: Handle server messages
The proxy created on previous step now needs to handle server messages. as seen in
my previous post The server calls Client.All.someMethod pseudo method where
someMethod is actually a message that is sent to the clients. There are several
extension method of the IHubProxy interface, the recommended on is the On method
which accepts the event name as string, and the arguments as a collection of parameters.
This is how it looks like:
We’ve used here two strings as a type parameters because the server sends two strings to the client
Here’s the corresponding server code.
Step 6: Invoke server methods
In here, we use another IHubProxy method (a non extension one this time) called Invoke.
This method accepts the server side method as a string and a collection of parameters.
This is how it looks like:
Where the corresponding server method named UpdateHomeTeamName and accepts
one string as a parameter.
programmer you can also interact with the server suing SignalR . The steps above
demonstrate how you can do this very easily.
The full code example can be found here
Enjoy, I’m sure you will.