SignalR with WPF – Part 2

In part 1 we discussed about SignalR, what it is and what it can do, we also wrote an example to establish the connection between the server and the client.. and send signal messages from client to server..

In this article we’ll do the opposite, send signal messages from server to the client..

We’ll just do a little modification in the client component which we developed in the previous article :-

static IHubProxy serverHub;

public void SendSignal(string msg)
{
var hubConnection = new HubConnection("http://localhost:8080/");
serverHub = hubConnection.CreateProxy("CollectionHub");
hubConnection.Start().Wait();
serverHub.Invoke("ClientSignalRecieved", msg);
}

1. We’ll now create an initialization function InitializeSignalR() and move the common code in it and call it in the constructor MainWindow() as we did in the server component, and in the client function we’ll just use the hub proxy to invoke the server function as follows :-

static IHubProxy serverHub;

public void InitializeSignalR()
{
var hubConnection = new HubConnection("http://localhost:8080/");
serverHub = hubConnection.CreateProxy("CollectionHub");
hubConnection.Start().Wait();
}

public void SendSignal(string msg)
{
serverHub.Invoke("ClientSignalRecieved", msg);
}

2. Now let’s write the function RecieveSignal(..) which will be called from the server side and register it on the hub proxy using the function On(..) in the InitializeSignalR() function


public void InitializeSignalR()
{
var hubConnection = new HubConnection("http://localhost:8080/");
serverHub = hubConnection.CreateProxy("CollectionHub");
serverHub.On("RecieveSignal", new Action<string>(RecieveSignal));
hubConnection.Start().Wait();
}

public void RecieveSignal(string msg)
{
Dispatcher.Invoke(new Action(() => txtInfo.Text += "message recieved: " + msg + " \n"), DispatcherPriority.Background);
}

3. Now to call it from the server hub, write the following line:-

Clients[Context.ConnectionId]
.RecieveSignal("send this");

That’s it, hope that was simple and useful 🙂

Leave a comment