Thursday, October 30, 2014

SignalR - C# Client

Intro

In Part 1 of this duet of posts I gave a brief overview of WebSockets, creating a basic SignalR server, and a JavaScript/html SignalR client. Here in the 2nd part we'll see how to create a C# client of SignalR. For the example we'll be using a WinForms project, but you could easily adapt this to a console program, windows service, WPF, DLL, or whatever you desire in C#. On to the code!


Code Sample

First, here's where we left off with our code last week. Download it and open it up in VS 2013. Review Part 1 if you're fuzzy on how some of this stuff works then come on back.

We'llstart today's coding by creating a new WinForms application in VS Express 2013. Go ahead and create yours. I've named mine BlogSignalRClient. Open up Form1 in designer view and add a textbox. Make it MultiLine and give it both scroll bars.

Now add the Microsoft.AspNet.SignalR.Client NuGet package to the new project. Open up the Form1.cs file in code view and paste in the following code:

using Microsoft.AspNet.SignalR.Client;
using System;
using System.Windows.Forms;

namespace BlogSignalRClient
{
    public partial class Form1 : Form
    {
        public IHubProxy HubProxy { get; set; }
        public const string ServerUrl = "http://localhost:61376/";
        public HubConnection Connection { get; set; }

        public async void Connect()
        {
            Connection = new HubConnection(ServerUrl);
            HubProxy = Connection.CreateHubProxy("NotificationHub");
            await Connection.Start();
            HubProxy.On("BroadcastMessage", (message) =>
                this.Invoke((Action)(() =>
                    textBox1.AppendText(String.Format("{0}" + Environment.NewLine, message))
                ))
            );
        }

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Connect();
        }

    }
}


You'll notice that in the Load event we're calling our Connect method. This creates a connection to the SignalR Hub named "NotificationHub" that we created last week. It then creates an instance of HubProxy that will mirror the methods from our SignalR hub. It then opens up the connection, and finally creates an event on the proxy such that when a message is broadcast via the BroadcastMessage method, we will respond in the app by adding the message to our textbox.

Let's test this sucker. If you haven't already, open up last week's project in Visual Studio 2013 and run it. Navigate to the admin.html page as it's where we send messages. Take note of the port you have in your browser window, and modify the code from above appropriately. Now launch the new WinForms app. Click back on your browser window again and type something into the box, then click the Disseminate button.


Click back on your WinForms app again and voila! You should see the message displayed in your textbox.



What's Next?

That's about it for my foray into SignalR. I suggest you experiment with it on your own, see what apps you can think of that would benefit from a real-time 2-way conversation and make them.

Resources

Using SignalR in WinForms and WPF
My WinForms SignalR Code

4 comments:

  1. This is what I was looking for. I want a Windows Service to publish to a Windows Forms Client that is subscribed to the service and can also make requests. WCF is such a pain!

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
  3. Perfecto!! solo una pregunta como le puedo responder al servidor??

    ReplyDelete