Real-time messaging app using SignalR and AngularJS

This article will demonstrate making a real-time messaging app using SignalR and AngularJS using Visual Studio 2015 and .NET 4.6.

Asp.net SignalR brings perhaps the easiest way to add duplex communication between server and client application. SignalR pushes content to the clients instantly as it becomes available. This makes SignalR an ideal candidate for realtime messaging applications as well real-time dashboards. Here client can be web form, windows application or even mobile application.

Let’s start developing this small app then.

Create new empty ASP.NET MVC project. Name it MessagingApp.
SignalR is available as a Nuget package and it is preferred way of installing it. Just search for SignalR in Nuget Package Manager and install it.

Add OWIN startup class
Now it’s time to add OWIN startup class. The OWIN (Open Web Interface for .NET) is a specification that defines an API for client and server communication. Main objective of OWIN is to decouple client and server and SignalR is built on OWIN. To add OWN startup class, just choose OWIN Startup class under Add New Item -> Web -> General. We will name this class as Startup. Once you add the class, put following line of code inside it:

using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(MessagingApp.Startup))]

namespace MessagingApp
{
    public class Startup
    {
         public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}

The MapSignalR method maps SignalR hubs to the app builder pipeline at "/signalr”. We will see this in in action when we first run the application.

Add AngularJS core
We will use AngularJS for the client code and we need to install AngularJS.Core NuGet package for the same. For this right click the solution explorer and choose Manage NuGet packages and search for AngularJS.Core. Once you find it, just install it.

Create SignalR hub
SingalR hub is server side component and they listen to any incoming request. The hub can also push/invoke methods on any number of clients which are connected to them. This duplex communication is achieved through web socket or long polling mechanism.  Let’s add the SignalR hub class to the project. To do so, right click on the project and choose Add New Item -> Web -> SignalR Hub Class. Name it MessageHub.

When you add this class, you will see that it includes method called Hello(). Simply remove that and put following code instead:

using Microsoft.AspNet.SignalR;

namespace MessagingApp
{
    public class MessageHub : Hub
    {
         public void SendMessage(string name, string message)
         {
             Clients.All.broadcastMessage(name, message);
        }
    }
}

We will call this above defined method from AngularJS code. This method broadcasts the message to all the connected clients. All in real time!

Create AngularJS client application
We will simply add an html file, named index.html to the project. After that we will put following piece of code in it:

<body ng-app="messagingapp">
    <div ng-controller="MessageController">
        <div>
            Name: <input type="text" ng-model="name" /><br />
            Message: <input type="text" ng-model="message" /><br />
            <input type="button" value="Send" ng-click="newMessage()" />
        </div>
        <div>
            <ul>
                 <li ng-repeat="message in messages">
                     <span ng-bind="message"></span>
                 </li>
            </ul>
        </div>
    </div>

    <script src="Scripts/jquery-1.6.4.js"></script>
    <script src="Scripts/jquery.signalR-2.2.0.js"></script>
    <script src="signalr/hubs"></script>
    <script src="Scripts/angular.js"></script>
</body>

The one thing you will notice in this code is that signalr/hubs path doesn’t exist. Remember MapSignalR method we called in OWIN startup class? That method will map SignalR hubs to the app builder pipeline at "/signalr”!

At this point press F5 to test that what we have done so far builds fine and run. Now if you navigate to the url that is shown in the figure below, you will see the mapped auto generated proxy of SignalR hub.


Note that in above url, the port number could be different for you.
For our article, we will not use this auto generated proxy but we will simply code it. For that, let’s add JavaScript file named messaging.js to the Scripts folder. After that put following piece of code in that:

(function () {
    var app = angular.module('messagingapp', []);

    app.controller('MessageController', function($scope) {
        $scope.name = 'Robot';
        $scope.message = '';
        $scope.messages = [];
        $scope.messageHub = null;

        $scope.messageHub = $.connection.messageHub;
        $.connection.hub.start();

        $scope.messageHub.client.broadcastMessage = function(name, message) {
            var newMessage = name + ' : ' + message;

            $scope.messages.push(newMessage);
            $scope.$apply();
        };

        $scope.newMessage = function() {
            $scope.messageHub.server.sendMessage($scope.name, $scope.message);

            $scope.message = '';
        }
    });
}());

We need to revisit the index.html file and put following one line to reference the newly added messaging.js file.

<script src="Scripts/messaging.js"></script>

Now it’s time to hit F5 again and see everything into action! Just open two window side by side pointing to same index.html and start posting messages in them. You will see that messages are broadcasting between two windows in real time and you can test it with more than two windows actually.


You can download the code here:
https://www.dropbox.com/s/i81uttnjzs55r4o/MessagingApp.zip?dl=0


By jay nanavati   Popularity  (4588 Views)