Book Image

SignalR Real-time Application Cookbook

By : Roberto Vespa
Book Image

SignalR Real-time Application Cookbook

By: Roberto Vespa

Overview of this book

Table of Contents (18 chapters)
SignalR Real-time Application Cookbook
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Connecting to a Hub from a JavaScript client


After having illustrated the two different ways we have to expose a server-side Hub let's now move on and see the client-side code in more detail.

During the Adding a Hub to an ASP.NET project recipe, we quickly used the JavaScript client library in order to demonstrate that our Hub was fully functional, but we did not go much into detail about it because we were concentrating on the server-side code. This recipe will fill this gap and give more clarity on how a JavaScript client is written. However, in order to make it fully functional, we will need a server-side portion; therefore, we'll be adding a basic Hub the same way we did for the Adding a Hub to an ASP.NET project recipe. Any specific detail about how to do it will be skipped because it's just an accessory to the real goal of this recipe, and we will just list the necessary steps. For any further clarification about that part, you can check the Adding a Hub to an ASP.NET project recipe.

Getting ready

Let's create a website where we'll be hosting our client. This is a common task, so we are going to skip the details. If you want more information about this, you can refer to Appendix A, Creating Web Projects at the end of the book.

How to do it…

We're ready to actually start adding what we need to build our SignalR client. We need to use the following steps:

  1. As we did in the Adding a Hub to an ASP.NET project recipe, we'll add a Hub called EchoHub and a Startup class. Here, we'll skip all the related details for brevity. Just make sure that the project ends up containing the same server-side code. These actions will download and add all the SignalR-related references, including the JavaScript client libraries.

  2. Let's add a web page to which we'll add our client. From the Project menu, select Add New Item, click on the Web folder, select the HTML Page template (specifying, for example, index.html as the name), and click on OK.

Visual Studio will create the specified file with some basic HTML content; let's edit it to make it look like the following:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-2.1.0.js"></script>
    <script src="Scripts/jquery.signalR-2.0.2.js"></script>
    <script src="/signalr/hubs"></script>
    <script>
        $(function () {
            var hub = $.connection.echo;
            $.connection.hub
                .start()
                .done(function () {
                    hub.server.say('Hello SignalR!');
                });
        });
    </script>
</head>
<body>
</body>
</html>

We basically kept what was there and just added the highlighted <script> blocks that you can see in the previous code.

We can now launch the application from Visual Studio; a browser window will open and the index.html page will be loaded. Then we'll observe the code reaching the Trace.WriteLine(message); line inside the Say() method of the EchoHub class as soon as the page is completely loaded in the browser.

How it works…

Let's concentrate on our client page. The details are as follows:

  • The first relevant portion of code are the first two <script> blocks, where we reference jquery and jquery.signalR as JavaScript libraries. jQuery is necessary because the SignalR JavaScript client is actually a jQuery plugin, as the actual name of the library makes clear.

  • Our libraries are taken from the /scripts folder, where they have been placed by one of the NuGet packages installed as soon as we added our Hub. This package is actually called Microsoft ASP.NET SignalR JavaScript Client and can be installed in any ASP.NET application, even if the application does not contain any Hub. We'll see how this can be useful in future recipes, where we will be trying to connect to Hubs hosted in a different web application from the one containing the client.

  • The third <script> block refers to a dynamic endpoint (/signalr/hubs) exposed by the server portion because of the MapSignalR call from the Startup class, already explained in the previous recipes. It actually generates JavaScript code on the fly according to the available Hubs. In practice, the JavaScript proxies for our Hubs (in this case, the EchoHub Hub) are built on the fly by the server-side portion of SignalR as soon as this endpoint is hit, and they're sent to the client as JavaScript source code.

  • The last <script> block is where we actually connect to our Hub. Let's dig more into it. The details are as follows:

    • Our code is written inside a classic jQuery $(...); call, which actually ensures that our code is called when the page is fully loaded.

    • We first take a reference to our echo Hub, which is exposed by the $.connection.echo property generated by the dynamic endpoint that we just described.

    • Then we call the start() method exposed by the $.connection.hub member, which performs the actual connection to our server.

    • The start() call is asynchronous, and we have to make sure it has actually been completed before using any Hub; that's easy because start() returns a promise object containing a done() method to which we can pass a callback function, where we put our Hub-related code. This way, we are sure that SignalR will call our code when the Hub proxy is fully initialized and ready to be used.

    • Inside our callback function, we can use our Hub instance; in particular, it's the server member from which we are able to call any method exposed by the Hub. The hub.server.say('Hello SignalR!'); line of code will actually call the Say() method on our server-side Hub.

    • Note that say is written in lowercase here. Regardless of the actual name on the server-side Hub, in a JavaScript context, SignalR automatically generates camel case names in order to provide a more idiomatic JavaScript API.

When launching the application from Visual Studio, a browser window will open, the page will be loaded, and the Say() method of the EchoHub class will execute as soon as the page is completely loaded.