Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
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
€22.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781783285952
Vendor :
Microsoft
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.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
€189.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
€264.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 111.97
SignalR Blueprints
€36.99
SignalR: Real-time Application Development - Second Edition
€32.99
SignalR Real-time Application Cookbook
€41.99
Total 111.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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.