2013-03-31

Connecting a .NET client (Console application) to a website with SignalR

On one of my previous posts, I’ve shown you how to build a web based chat application with the use of SignalR. SignalR isn’t only restricted to web clients. It also works with many other clients like iOS, Android (There are no official support for them yet though. Those projects are community driven at this stage.) and Silverlight, .NET clients. In this blog post, I’m going to show you how to integrate a .NET client to my already built web application.

Following is the link to the web application I’ve created using SignalR

http://ruchirac.blogspot.com/2013/02/creating-chat-application-in-aspnet.html

Now I’m going to connect my .NET client (Console application) to that hosted website. For that, first of all I have to install SignalR .NET Client for my Console application. I can either do it by manually adding the DLL files and adding the references to the project or install it directly using NuGet Package manager. Since Installing it via NuGet Package manager is a lot easier, I’m going to use that.

.net client

After installing the Microsoft ASP.NET SignalR .NET Client, we are ready to develop our application. Following is the code for the Console app

using Microsoft.AspNet.SignalR.Client.Hubs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleClient
{
    class Program
    {
        static void Main(string[] args)
        {
            var hubConnection = new HubConnection("
http://localhost:53748");
            var chat = hubConnection.CreateHubProxy("ChatHub");
            chat.On<string, string>("broadcastMessage", (name, message) => { Console.Write(name + ": "); Console.WriteLine(message); });
            hubConnection.Start().Wait();
            chat.Invoke("Notify", "Console app", hubConnection.ConnectionId);
            string msg = null;

            while ((msg = Console.ReadLine()) != null)
            {
                chat.Invoke("Send", "Console app", msg).Wait();
            }
        }
    }
}

At the first line, I’m connecting to the hosted website. In this example, the chat server. I’m using localhost because I’m using Visual Studio to run the application. If you’ve already hosted the application in somewhere else, then you have to give that web address to the HubConnection Constructor.

var hubConnection = new HubConnection("http://localhost:53748");

The above line will create a Connection to the Hub hosted in http://localhost:53748. We can use that to create a Hub Proxy. In my example, the hub name is ChatHub (The class name in server). So I’ve passed that to CreateHubProxy method. Then I’ve registered the method “braodcastMessage”, to display the messages on Console, app which I get from the other clients.

chat.On<string, string>("broadcastMessage", (name, message) => { Console.Write(name + ": "); Console.WriteLine(message); });

I’m getting two parameters from the server call, name and message. I’m writing them on the console as I get them. My server method looks like below

public void Send(string name, string message)
{
    // Call the broadcastMessage method to update clients.
    Clients.All.broadcastMessage(name, message);
}

As you can see, there I’m calling the method “broadcastMessage” on all clients. In the next line I’m starting the connection with the server.

hubConnection.Start().Wait();

I’m calling the Wait() method in order to wait till the connection made between server and my .NET client.

Next, I’m calling the Notify method in the server. It’s responsible for adding the connection ID to the client list and notifying other clients about the arrival of Console client.

chat.Invoke("Notify", "Console app", hubConnection.ConnectionId);

Here I’ve hardcoded the name “Console app”.

After that, I’m running a loop to get the messages from Console app. Then I invoke the server method as soon as I get a message from the .NET Client user. Then the server method, in this case “Send”, is responsible for broadcasting the message to all other connected clients.

string msg = null;

while ((msg = Console.ReadLine()) != null)
{
    chat.Invoke("Send", "Console app", msg).Wait();
}

So that’s all what it takes to build up a simple .NET client application which connects to a SignalR hub to do the real time communication. Following is a screenshot of how it looks like when it communicates with a web client.

SignalR console

9 comments:

mobile phones review said...

Your blog is really excellent.It inspires the readers.Thanks for sharing information .

Kermit Guerra said...

I fill really glad ,that I read your earlier article and now I also able to know how to Connecting a .NET client to a website with SignalR for better enhancement of .NET development work.

Anonymous said...

Hello! I made a winform project as a client. I want to display the message in the textbox. This is my code

private void connect_btn_Click(object sender, EventArgs e)
{
var hubConnection = new HubConnection("http://localhost:8080");
var hubProxy = hubConnection.CreateHubProxy("MyHub");

hubProxy.On("addMessage", (name, message) => { display_txt.Text = name + ": " + message; });
hubConnection.Start().Wait();

but I get this error.
"Cross-thread operation not valid: Control 'display_txt' accessed from a thread other than the thread it was created on." how can i fix this error? Thank you!

Ruchira Gamage said...

Hello,

I'm sorry, I'm not good with win forms. But I think the below link will help you

http://msdn.microsoft.com/en-us/library/ms171728.aspx

Vyom Sharma said...

Is it possible to interact my web based signalR chat system with android app do u have any idea about this?? or if you have any blog post related to it then please tell me any help is really appriciated

Ruchira Gamage said...

You can use SignalA library for Android.

Unknown said...

If you get this error in Visual Studio: The type or namespace name 'HubConnection' could not be found, just change the using statement to this:

using Microsoft.AspNet.SignalR.Client;

Camberley Web Design said...

Great post, thanks for sharing

krishna prasad said...

We implemented signal R in SL4 using javascript without moving to SL5 . Now the problem we are getting with Out of browser app in SL due to javascript is not loading because of Default.aspx file is not invoked which is web browser related. Can you please suggest any solutions how we can implement in OOB app using Javascript or any other options. If possible can you please give a sample how we can implement signalr client using websockets using WCF.