What is SignalR ?
from the official asp.net site, SignalR is a new library for ASP.NET developers that makes developing real-time web functionality easy. SignalR allows bi-directional communication between server and client.
Servers can now push content to connected clients instantly as it becomes available.
Communication between server and client could happen between .Net code and Javascript, It also could happen between two .Net applications which act as a client-server application.
What are the main components required to establish connection between client and server?
- Server component with a Hub which contains the functions that can be called from the client
- Client component with a Hub proxy which communicate with the server hub and invoke its methods, and also the Hub proxy can be used to register the client functions which can be called from the server
How to communicate between two WPF applications using SignalR?
- download the source code from here, open it in VS, compile it in release mode and get the following dlls:
- for client application add these dlls as reference:
SignalR.Client
- for server application add these dlls as references:
SignalR
SignalR.Hosting.Common
SignalR.Hosting.Self - In the Server application in “MainWindow.xaml.cs”, write an Initialization function to create the SignalR server, and call it in the constructor MainWindow()
public void InitializeSignalR() { string url = "http://*:8080/"; var server = new Server(url); server.MapHubs(); server.Start(); }
- In the Server application, create a Hub class by creating a custom class and inherit from Hub
// The exact name of the hub class you create will be used // to create the hub proxy in the client public class CollectionHub : Hub { public CollectionHub() { } // server function to change a TextBlock element in WPF public void ClientSignalRecieved(string msg) { // To access WPF elements from class other than the MainWindow // you can use the following code Application.Current.Dispatcher.Invoke(new Action(() => ((MainWindow)System.Windows.Application.Current.MainWindow).txtInfo.Text = msg), DispatcherPriority.Background); } }
- In the Client application, define a global static hub proxy
static IHubProxy serverHub;
then write the client functions to call the server functions created in the hub using the hub proxy
public void SendSignal(string msg) { // create a hub connection using the ip and port number // of the server component which carry the hub class var hubConnection = new HubConnection("http://localhost:8080/"); // create hub proxy using the hub name you created // to communicate with the server hub and invoke its methods serverHub = hubConnection.CreateProxy("CollectionHub"); // start the connection hubConnection.Start().Wait(); // use the hub proxy to invoke the server method and pass // the parameters needed by the function serverHub.Invoke("ClientSignalRecieved", msg); }
One thought on “SignalR with WPF – Part 1”