Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
SignalR Real-time Application Cookbook
SignalR Real-time Application Cookbook

SignalR Real-time Application Cookbook: Use SignalR to create real-time, bidirectional, and asynchronous applications based on standard web technologies.

eBook
$29.69 $32.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

SignalR Real-time Application Cookbook

Chapter 2. Using Hubs

In this chapter, we will cover:

  • Adding a method to a Hub and counting the calls to it

  • Calling back the caller from a Hub's method

  • Broadcasting to all connected clients

  • Adding a connection to a group

  • Removing a connection from a group

  • Broadcasting to all connected clients except the caller

  • Broadcasting to all clients except the specified ones

  • Broadcasting to all clients in a group except the caller

  • Broadcasting from outside a Hub

  • Using the return value of a Hub method

Introduction


SignalR's main goal is to deliver a real-time experience over HTTP, where both clients and servers can participate in a conversation as senders and listeners at the same time (known as full-duplex communication). A client initiates the flow by starting a new connection, but after that, both types of actors are equally capable of sending and receiving bits of the conversation.

In order to deliver such an experience, SignalR comes with two distinct APIs: one called persistent connection, which we can consider to be the low-level API, and one called Hubs, which is built on top of the former and brings a higher-level set of concepts and an easier and straightforward experience for the developer. We'll talk about Hubs first as we want to make our way through the SignalR features, starting from the simplest to use to the more sophisticated.

A Hub can be seen as a set of methods exposed by a server that any client can connect to, in order to perform actions on that server or to retrieve...

Adding a method to a Hub and counting the calls to it


This first recipe of the chapter is very simple, and in a way similar to the others we saw in Chapter 1, Understanding the Basics; however, the focus will be lesser on the process and the parts involved and more on specific Hub features. We'll learn a simple way to count how many times a Hub method is called by the connected clients.

Getting ready

Before writing the code of this recipe, we need to create a new empty web application, which we'll call Recipe05.

How to do it…

We're ready to actually start adding our SignalR bits by performing the following steps:

  1. Let's add a Hub called EchoHub. Behind the scenes, this action references a NuGet package called Microsoft.AspNet.SignalR, which then brings a few more packages.

  2. Then we add an OWIN Startup class named Startup, which contains just a simple app.MapSignalR() bootstrap call inside the Configuration() method.

  3. It is important to highlight the fact that it is recommended to add a Hub to the...

Calling back the caller from a Hub's method


With this recipe, we are actually starting to look at more interesting and real-time SignalR features. We will see how a Hub can call back into a client that just performed a remote method call.

Getting ready

Before starting with this recipe, we need to create a new empty web application, which we'll call Recipe06.

How to do it…

Let's start building the server-side portion of this recipe using the following steps:

  1. We must first add a Hub called EchoHub.

  2. We must then add an OWIN Startup class named Startup, containing just a simple app.MapSignalR(); bootstrap call inside the Configuration() method.

  3. Let's make the Hub's content look like the following:

    using System;
    using Microsoft.AspNet.SignalR;
    using Microsoft.AspNet.SignalR.Hubs;
    
    namespace Recipe06
    {
        [HubName("echo")]
        public class EchoHub : Hub
        {
            public void Hello()
            {
                var msg = string.Format("Greetings {0}, it's
                    {1:F}!",
                    Context...

Broadcasting to all connected clients


After several examples where a single client was involved at a time, we'll start looking at scenarios where multiple clients are connected at the same time, and we'll start making them interact. We will see how a Hub can call back into all the connected clients from the context of a single remote method call performed by just one of them. This is where SignalR becomes a more interesting and outstanding library!

Getting ready

Before proceeding, we need to create a new empty web application, which we'll call Recipe07.

How to do it…

As usual, we need some simple steps to get started as follows:

  1. Add a Hub called EchoHub.

  2. Add an OWIN Startup class named Startup with its Configuration() method containing just a simple app.MapSignalR(); bootstrap call.

  3. Modify the file content to make it look like the following code:

    using System;
    using Microsoft.AspNet.SignalR;
    using Microsoft.AspNet.SignalR.Hubs;
    
    namespace Recipe07
    {
        [HubName("echo")]
        public class EchoHub...

Adding a connection to a group


Multiple clients can connect to a specific Hub at the same time, and the number of connections can easily increase. SignalR offers a feature called groups in order to define subsets of connections and use them when broadcasting to clients. We will see how a Hub can place connected clients into groups and then broadcast calls to all the connections belonging to a specific group.

Getting ready

Before writing the actual code, we need to create a new empty web application, which we'll call Recipe08.

How to do it…

We're ready to start building our sample. We need to perform the following steps:

  1. Add a Hub called EchoHub.

  2. Add an OWIN Startup class named Startup with a Configuration() method calling app.MapSignalR();.

  3. Add the following to the Hub code:

    using Microsoft.AspNet.SignalR;
    using Microsoft.AspNet.SignalR.Hubs;
    
    namespace Recipe08
    {
        [HubName("echo")]
        public class EchoHub : Hub
        {
            public void Subscribe(string groupName)
            {
                Groups...

Removing a connection from a group


As we just saw, groups are an interesting and useful feature exposed by the Hub API. In the previous recipe, we concentrated on how to add connections to a specific group, but we did not expand on how you can remove them. This will be the subject of this recipe.

It's quite obvious that in order to remove connections from a group, we'll have to add them to it first; however, that part has already been covered by the previous recipe. Here we'll show the code to do both operations in order to deliver a fully working recipe, but we'll indulge in comments only for the removal part. For more details about adding connections to a group, please refer to the previous recipe.

Getting ready

Before proceeding, we create a new empty web application, which we'll call Recipe09.

How to do it…

We're ready to actually start adding our SignalR bits by performing the following steps:

  1. We need a Hub called EchoHub.

  2. We then need an OWIN Startup class named Startup containing just a...

Broadcasting to all connected clients except the caller


In the previous recipes, we saw a few examples of broadcasting where the sender was always included among the receivers of the message. That was because the APIs we used always included the sender, whether we used the Caller member, the All member, or the Group() method. There are several scenarios though, where it does not make sense to broadcast to the caller; for example, in a live forum application, where it might be enough to broadcast each message to everybody who joined except the sender. That's why SignalR offers the Others member in order to send calls to everybody but the caller. Let's use it.

Getting ready

Before writing the code of this recipe, we need to create a new empty web application, which we'll call Recipe10.

How to do it…

This is a simple Hub. To make it work, we need to perform the following steps:

  1. Add a Hub called EchoHub.

  2. Add the usual OWIN Startup class, which we name Startup, containing the Configuration() method...

Broadcasting to all clients except the specified ones


SignalR offers a couple of ways to exclude entire sets of connections from a broadcast; here, we see how we can exclude a specific set of connected clients using their ConnectionId properties.

To demonstrate this feature, we need a slightly more complex sample. Let's consider a case where some of the messages should go unobserved by the specific clients we do not want to target. In such a case, we would need to inform everybody about who else is connected, and provide a way to pick some of those in order to exclude them from the next broadcast. To achieve this, we store a list of all the received connections in a static Hashset member inside the hub, and we send this set to every connected client when it calls a Subscribe() method. This set of connections will be used by the client to show a list of identifiers from which the user can select who to exclude when performing the broadcast of the message. To keep the UI simple, we'll let the...

Broadcasting to all clients in a group except the caller


Similar to what we just did in order to exclude specific connections from the set of all the connected clients, we can provide exceptions in the context of a specific group. We can broadcast to all the connections in a given group, excluding a list of specific ConnectionId values that we want to omit.

Getting ready

Before writing the code of this recipe, we create a new empty web application, which we'll call Recipe12.

How to do it…

Let's prepare our project by performing the following steps:

  1. We add a Hub called EchoHub.

  2. Let's then add the usual OWIN Startup class named Startup, with a Configuration() method calling app.MapSignalR().

  3. Let's edit Hub's content using the following code:

    using Microsoft.AspNet.SignalR;
    using Microsoft.AspNet.SignalR.Hubs;
    
    namespace Recipe12
    {
        [HubName("echo")]
        public class EchoHub : Hub
    {
            public void Subscribe(string groupName)
            {
                Groups.Add(Context.ConnectionId, groupName...

Broadcasting from outside a Hub


All the recipes we illustrated so far have a common workflow as follows:

  • A client starts a connection first

  • The same client calls at least one method on the Hub

  • Eventually, any sequence of client-to-server and server-to-client calls can happen

Given the precondition of starting a connection from the client, which cannot be skipped, the fact that we then need at least one client-to-server call at the beginning, before doing anything else, may not be ideal. What if we want to start a conversation directly from a Hub? There's no such limitation with SignalR. In fact, a Hub may well be the first one to call back into the clients (already connected). There are a couple of ways to do it: the first one involves connection events, which will be illustrated in Chapter 6, Handling Connections, while the other option is based on the fact that a Hub can be used by any server-side code outside the Hub itself. This indeed becomes a mechanism to perform server-to-client calls...

Using the return value of a Hub method


So far, we examined different ways to push information from a server Hub to the connected clients; in particular, we saw how to perform a client-side call just on the caller in the Calling back the caller from a Hub's method recipe. All these techniques have one thing in common: the remote call is performed through the Clients member exposed by Hub. However, in the special case of communicating just with the caller, we can use a different, and in some way more natural, way to do it: have the Hub method return a value.

Getting ready

For this recipe, we need a new empty web application, which we'll call Recipe13.

How to do it…

We're ready to start adding our SignalR stuff, as usual. We need to perform the next set of steps:

  1. Add a Hub called EchoHub.

  2. Add an OWIN Startup class named Startup, containing just a simple app.MapSignalR(); bootstrap call inside the Configuration() method.

  3. The following code needs to be added to the Hub:

    using System;
    using Microsoft...
Left arrow icon Right arrow icon

What you will learn

  • Teach you how to build SignalR servers
  • Illustrate SignalR clients built with both the JavaScript and the .NET client libraries
  • Demonstrate both the Hubs API and the Persistent Connection API
  • Demystify the lifetime of a connection
  • Explain how to authorize requests
  • Scale up and scale out your SignalR applications
  • Enable you to handle errors efficiently
  • Extend SignalR with custom services
  • Solve complex realtime scenarios with the help of advanced, readymade examples

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 23, 2014
Length: 292 pages
Edition :
Language : English
ISBN-13 : 9781783285969
Vendor :
Microsoft
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Apr 23, 2014
Length: 292 pages
Edition :
Language : English
ISBN-13 : 9781783285969
Vendor :
Microsoft
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 147.97
SignalR Blueprints
$48.99
SignalR: Real-time Application Development - Second Edition
$43.99
SignalR Real-time Application Cookbook
$54.99
Total $ 147.97 Stars icon

Table of Contents

8 Chapters
Understanding the Basics Chevron down icon Chevron up icon
Using Hubs Chevron down icon Chevron up icon
Using the JavaScript Hubs Client API Chevron down icon Chevron up icon
Using the .NET Hubs Client API Chevron down icon Chevron up icon
Using a Persistent Connection Chevron down icon Chevron up icon
Handling Connections Chevron down icon Chevron up icon
Analyzing Advanced Scenarios Chevron down icon Chevron up icon
Building Complex Applications Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.6
(9 Ratings)
5 star 66.7%
4 star 22.2%
3 star 11.1%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




S. Aki Feb 23, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I was studying another SignalR book and just didn't get anywhere satisfactory so ended up forking out for yet another book. Wish I'd gotten this one first!Teaches you how to implement SignalR in MVC, Web Forms and even plain HTML.This book really impressed me when the last few programming related books I've read have all been very dry and unexciting.
Amazon Verified review Amazon
Amazon Customer Jun 09, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I like this book. It introduces many wonderful information for my development!
Amazon Verified review Amazon
Amazon Customer Jul 14, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Real impressive book covering all aspects of SignalR, from using and understanding Hubs and Connections right through to real-world examples. The best thing about this book is it contains real good examples you could always reference. Overall 5 out of 5, a theoretical book with practical examples!
Amazon Verified review Amazon
Charlie J. Biggs Jun 12, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great insight into a very open and flexible technology. The Cookbook is well written and provides easy to follow recipes for implementing Signalr into your application. I refer to it on a regular basic as I architect and implement Real-time logic into my enterprise application.Charlie J.
Amazon Verified review Amazon
Jacob Cheriathundam Aug 24, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
SignalR itself is a pretty great technology to use when WebSockets can't be relied upon (considering the breath of browsers out there, web sockets just can't be relied on solely for any push functionality). This book made it easy to learn and implement SignalR into your solutions. I knew nothing about it before I started and I've already implemented in 3 of my existing projects and plan to use it on a few more.While the redundancy of putting the same template code over and over again takes up space, I can see how that would also be beneficial if someone just picked up the book to learn about implementing a single strategy. They could simply skip to the chapter(s) of concern and quickly get a solution rather than reading the whole book to make sure everything is setup correctly.Fantastic book and would highly recommend it to anybody that is trying to learn SignalR.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.

Modal Close icon
Modal Close icon