Tallan's Blog

Tallan’s Experts Share Their Knowledge on Technology, Trends and Solutions to Business Challenges

Using SignalR for a Real-time Web App

Overview

SignalR is a library in ASP.Net that allows the real-time updating of data between server and client. It proactively pushes content to connected clients instead of waiting for the clients to send a request. This can be leveraged to replace polling and eliminates the need to refresh pages. SignalR also allows management for connections between servers and clients to determine this real-time communication. This functionality can be used from anything ranging from, but not limited to, games to notifications. In this post, I will examine the basic components and set-up of SignalR for an ASP.NET Web App.

Components

There are two main pieces to using the SignalR API: Connections and Hubs.

Connections are the endpoints that represent a user and are used to send content in broadcasts. They can be sent by themselves, or to groups of subscribed users, allowing for greater control and customization.

Hubs allow client and server direct communication between client and server-side methods. They have the added advantage of being able to send strongly typed parameters and therefore enabling model-binding.

Set up

We can add SignalR to the project either through the Solution Explorer UI by adding a SignalR Hub Class or via Package Manager Console in Visual Studio. If you elect to use the Package Manager Console, run the following command, and then create a SignalR hub class manually afterward. We’ll call it MessageHub

install-package Microsoft.AspNet.SignalR

After this, if we navigate to the Scripts folder in the Solution Explorer, we’ll see jQuery and SignalR libraries.

In the Hub class added through the Solution Explorer, we can add in a method to broadcast a message to connected clients that will be called from the client side:

public void Send(string message)
{
    // Call the sendMessage method to push to clients.
    Clients.All.sendMessage(message);
}

If your app doesn’t have an OWIN Startup Class, add one to your project. In the Configuration method of the Startup Class, we can add configurations and connections for hubs. Be sure to include

app.MapSignalR();

The last component we need to get started is on the client side. In our Html page, the scripts for jquery, SignalR, and Hubs must be referenced as well as JavaScript text for page updates:

<script src="Scripts/jquery-3.1.1.min.js"></script>
<!--SignalR library reference-->
<script src="Scripts/jquery.signalR-2.2.1.min.js"></script>
<!--Autogenerated SignalR hub script reference-->
<script src="signalr/hubs"></script>
<script type="text/javascript">

Lastly, we must wire up the Hub to the client. Add a reference either through script tags or a separate script reference. Creating a separate JavaScript file and referencing it is recommended for extensibility.  In this script we’ll add a reference to the server hub and a connection initializer:

 $(function () {
    //Stored reference to the hub.
    var messageHub = $.connection.MessageHub;
    //Initialize the connection.
    $.connection.hub.start().done();
});

Usage

Now that the pieces are in place, we can modify functionality based on what is needed. Here we can assume the markup has a button with id “sendMessage”. We can call our Hub “Send” method from the client when it is clicked like so:

$('#sendMessage').click(function () {
                    // Call the Send method on the hub.
                    messageHub.server.send($('#message').val());
});

This will cause the value of the element with the id of “message” in say, a textbox, to be sent to the Hub.

Since SignalR is two-way communication, the client needs a method called sendMessage that the Hub called:

// Function for the hub to call to send Messages to all connected clients.
messageHub.client.broadcastMessage = function (message) {
    // Add the message to the page.
    $('#messageBox').append('<li>' + message + '</li>');
    };

This brief example demonstrates how the Hub and client can call each other and push content. When the page with this front end is opened in two different windows and a message is sent, both connected clients will see the pushed content simultaneously. We added the SignalR library, a hub class, and client-side code that work in conjunction to send messages to the client(s). Based on functional requirements, there can be a lot of other uses added such as using OnConnected() overrides to track connected clients or more complex ways to display pushed content with jQuery. This is a useful tool in providing real-time functionality as needed. More info can be found at http://signalr.net/.


If you are interested in getting additional help with your web apps check out our Web Solutions Page and Contact Us today, or see us in-person at one of our many Events

No comments

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

\\\