Server Broadcast (Send notifications from server to clients) using ASP.NET SignalR

ASP.NET SignalR is a library for ASP.NET developers that simplifies the process of adding real-time web functionality to applications. Real-time web functionality is the ability to have server code push content to connected clients instantly as it becomes available, rather than having the server wait for a client to request new data – Microsoft

Normally server sends notifications to clients when communication is initiated by some client but there are situations when we want server to push data to clients even there is no request from any clients.
Here is step by step procedure to do so.

Step 1
Add hub class, right click (on the App_Code in case of website project or appropriate folder in case of web application project), select Add and then Add New Item. Select the SignalR Hub Class template, give it a name say BroadcasterHub and click Add.
Your class should look like below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
    [HubName("mainBroadcasterHub")]
    public class BroadcasterHub : Hub
    {
        private readonly Broadcaster _broadcaster;
        public BroadcasterHub() : this(Broadcaster.Instance) { }

        public BroadcasterHub(Broadcaster broadcaster)
        {
            _broadcaster = broadcaster;
        }
    }

Note: Remember this HubName attribute, we will use it later.

Step 2
Now add broadcaster class, right click (on the App_Code in case of website project or appropriate folder in case of web application project), select Add and then Add New Item. Select the Class template, give it a name say Broadcaster and click Add.
Your class should look like below:

using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
    public class Broadcaster
    {
        private readonly static Lazy<Broadcaster> _instance = new Lazy<Broadcaster>(() => new Broadcaster(GlobalHost.ConnectionManager.GetHubContext<BroadcasterHub>().Clients));
        public static Broadcaster Instance
        {
            get
            {
                return _instance.Value;
            }
        }

        private IHubConnectionContext<dynamic> Clients
        {
            get;
            set;
        }
        private Broadcaster(IHubConnectionContext<dynamic> clients)
        {
            Clients = clients;
        }
        public void SendNotification(string notificationContent)
        {
            Clients.All.onNotification(model);
        }
    }

Step 3
Add Owin Startup Class to your project if it is not there, right click (on the App_Code in case of website project or appropriate folder in case of web application project), select Add and then Add New Item. Select the Owin Startup Class template, give it a name say Startup and click Add.
Add the call to app.MapSignalR() in Configuration method, your class should look like below:

using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(Startup))]
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
         app.MapSignalR();
	  //Other code
        }
    }

Step 4
Add jQuery and SignalR script references in your page:

<script src='/Scripts/jquery.js'></script>
<script src='/Scripts/jquery.signalR-2.1.2.js'></script>			
<script src='/signalr/hubs'></script>

Step 5
Add the following code on the page to establish the connection with hub and also to write client side function to be called by server while sending notfication.

<script>
 $(document).ready(function () {
  var broadcaster = $.connection.mainBroadcasterHub; // this is the name we gave in HubName attribute in hub class	
      broadcaster.client.onNotification = function (notificationContent) {
         alert(notificationContent);
        };                   
      $.connection.hub.start().done(function (state) { });
  });
</script>

Where onNotification is the client side function we call from broadcaster class. You can pass complex type parameters to this method. Also you can display the received data in whichever format you want instead of using the alert function.

Step 7
Send notification from your server side code as given below:

protected void btnSendNotification_Click(object sender, EventArgs e)
    {        
        Broadcaster.Instance.SendNotification("This is a test notification");
    }
Comments
Share it

Leave a Comment

Your email address will not be published. Required fields are marked *