Sony Arouje

a programmer's log

Archive for September 2014

Chat application using SignalR 2.1

with 8 comments

Around two years ago I published a post about SignalR. Recently some readers requested an updated post using SignalR 2.1, here is the updated one.

For this post I created a very simple chat application that hosted in IIS, developed in .NET 4.5. Below is the project structure.

  • SignalrTracer.ChatServer: An empty ASP.NET Web Application which host the SignalR hub.
  • SignalrTracer.Publisher: A class library project that has SignalR hubs. I created this project just to isolate SignalR hubs from the ChatServer.
  • SignalrTracer.ChatClient: Another empty ASP.Net Web Application act as the client.

 

SignalrTracer.Publisher

As I mentioned above, this project contains the SignalR hubs. We can add SignalR framework using Nuget package manager.

Open Package Manager Console from Tools->Nuget Pacakger Manager and choose SignalrTracer.Published as the Default Project in the console window, then enter

PM> Install-Package Microsoft.AspNet.SignalR.Core

The command will add the SignalR and dependent frameworks. It’s time to create our chat hub.

ChatHub.cs

using Microsoft.AspNet.SignalR;
namespace SignalrTracer.Publisher
{
    public class ChatHub:Hub
    {
        public void Subscribe(string chatId)
        {
            Groups.Add(Context.ConnectionId, chatId);
        }

        public void Publish(string toChatId, string message)
        {
            Clients.Group(toChatId).flush(message);
        }
    }
}

 

SignalR 2.1 relies on OWIN to host it. For that we need to create a Startup class as shown below.

using Microsoft.Owin;
using Owin;
using Microsoft.AspNet.SignalR;
[assembly: OwinStartup(typeof(SignalrTracer.Publisher.Startup))]
namespace SignalrTracer.Publisher
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
            var hubConfig = new HubConfiguration();
            hubConfig.EnableDetailedErrors = true;
            hubConfig.EnableJSONP = true;
            app.MapSignalR("/chatserver", hubConfig);

            app.Run(async context =>
            {
                await context.Response.WriteAsync("Chat server started");
            });
        }
    }
}

That’s it we created our SignalR hub. Let’s host it in our ChatServer.

SignalrTracer.ChatServer

This project is a OWIN host, to do that we need to refer another Nuget package called Microsoft.Owin.Host.SystemWeb.

Open the Nuget Package Manager Console and set Default project as SignalrTracer.ChatServer, then enter

PM> Install-Package Microsoft.Owin.Host.SystemWeb

Once all the package installed, just refer SignalrTracer.Publisher project and run the project. If every thing is fine then you can see an Internet Explorer with a string Chat server started. This means SignalR hub is up and running and any clients can connect now.

 

SignalrTracer.ChatClient

I used Javascript to connect to SignalR server. Open Nuget Package Manager Console and enter

PM> Install-Package Microsoft.AspNet.SignalR.JS

It will install JQuery and JQuery extension of SignalR client. I created an index.html and added the code below.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script src="Scripts/jquery-1.6.4.min.js"></script>
    <script src="Scripts/jquery.signalR-2.1.2.min.js"></script>
    <script type="text/javascript">
    $(function () {
        var connection = $.hubConnection('http://localhost:35144/chatserver');
        var proxy = connection.createHubProxy('ChatHub');
        connection.start()
                .done(function () {
                    $('#messages').append('<li>Connected to chat</li>');
                })
                .fail(function () { alert("Could not Connect!"); });

        proxy.on('flush', function (msg) {
            $('#messages').append('<li>' + msg + '</li>');
        });

        $("#send").click(function () {
            proxy.invoke('Publish', $("#sendTochatId").val(), $("#message").val());
        });

        $("#connect").click(function () {
            proxy.invoke('subscribe', $("#chatId").val());
            $('#messages').append('<li>subscribed to chat</li>');
        });
    });
    </script>

    <title></title>
</head>
<body>

    <label>Chat id</label> <input type="text" id="chatId" /><input type="button" id="connect" value="Connect" /><br />
    <label>Send To</label> <input type="text" id="sendTochatId" /><br />
    <label>Message</label> <input type="text" id="message" />
    <input type="button" id="send" value="Send"/>
    <div>
        <ul id="messages"></ul>
    </div>
</body>
</html>

 

You might need to change the url of hubConnection marked in bold.

Once the connection established messages section will get appended with ‘Connected to chat’ message.

Enter a unique Id in Chat Id text and click Connect, open multiple window and connect with different chat id’s.

 

As you can see it’s a very basic and simple chat system based on SignalR.

Source Code

Happy coding…

Written by Sony Arouje

September 18, 2014 at 12:49 am

Posted in .NET

Tagged with ,

%d bloggers like this: