Broadcasting Messages with SignalR using Angular & .NET Core API

Akanksha Singh
Globant
Published in
6 min readJan 13, 2022
PC: Google Images

This article gives a brief introduction of using SignalR to broadcast messages to a real time web application.

After reading this article, you:

  • Get Basic overview of Signal R and its application in real world scenarios.
  • Set up the project.
  • Examine the code.

Prerequisites

There are some perquisites for this article. You should have an overview of exposing CRUD operation in REST API & consuming the same via any web application. For this article, I have used Angular 9 (Compatible to all version of angular) to consume & display data.

Tools/Framework/Language

Introduction

SignalR is a open source library to simplify 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.

It provides a simple API for creating server-to-client remote procedure calls (RPC) that call JavaScript functions in client browsers (and other client platforms) from server-side .NET code. It also includes API for connection management (for instance, connect and disconnect events), and grouping connections. It handles connection management automatically, and lets you broadcast messages to all connected clients simultaneously, like a chat room. You can also send messages to specific clients. The connection between the client and server is persistent, unlike a classic HTTP connection, which is re-established for each communication.

SignalR supports “server push” functionality, in which server code can call out to client code in the browser using Remote Procedure Calls (RPC), rather than the request-response model common on the web today.

SignalR applications can scale out to thousands of clients using built-in, and third-party scale-out providers.

SignalR and WebSocket

SignalR uses the new WebSocket transport where available and falls back to older transports where necessary. While you could certainly write your app using WebSocket directly, using SignalR means that a lot of the extra functionality you would need to implement is already done for you. Most importantly, this means that you can code your app to take advantage of WebSocket without having to worry about creating a separate code path for older clients. SignalR also shields you from having to worry about updates to WebSocket, since SignalR is updated to support changes in the underlying transport, providing your application a consistent interface across versions of WebSocket.

Applications of SignalR

  1. Notification: If you want to notify single client or all clients then we can use SignalR. Notification can be like some alerts, a reminder, feedback or comments and so on.
  2. Chat: It is very easy to implement a chat application using SignalR, either it could be one-to one or a group chat.
  3. Gaming: SignalR helps to create a Gaming application that requires frequently pushing from a server and so on.

Use Case in which I have used Signal R

In one of the projects which deals with bulk amount of data and many users, we were using timers that was making calls in specific intervals to server to know work(it can be approval/reject scenario or file imports, etc.) status based on which clients needed to be notified with work done status. These timers affected the performance of application when there is considerable good amount of users.

So to improve performance, we opted to use SignalR to let server notify the client if they are any updates happening in background.

Lets show some code…

To understand how SignalR works, I created a web application which aims to manage employees & managers. When we perform CRUD operations on employee data, we will get broadcasted message from SignalR hub in the Angular application and immediately show the modified data in all connected client browsers.

To be able to use SignalR, we need to add it as a NuGet package in API and as npm package in node modules.

Steps

1. API Endpoints

  • In Visual Studio, create an ASP.NET Core Web API Application.
Fig-#1
  • After clicking Next, choose the target framework to be used. For this article, I have used .NET 5.0.

Note:- We opted for default “Enable Open API support” option. This feature will help us to enable swagger API documentation in our application.

Fig-#2
  • We can now create CRUD operations for our API. To know about the to-do steps of the same, we can take reference of Web API Creation.
  • We can install the NuGet package “Microsoft.AspNet.SignalR” now.
  • To install the NuGet package, we can navigate to Package Manager Console and enter the following command:

Install-Package Microsoft.AspNet.SignalR -Version 2.4.2

Fig-#3

2. SignalR Code Configuration

  • We have created IHubClient interface and BroadcastHub class to broadcast real-time messages to Angular application. Both interface and class will be used to broadcast real-time messages to Angular application.
Fig-#4

Note:- BroadcastHub inherits from Hub<IHubClient>. Hub Class provides methods that communicate with SignalR connections that connected to a Hub.

Fig-#5

3. Startup.cs changes and creating Notification Hub

Fig-#6

Make sure you have called CORS middleware before registering SignalR. We can dig in depth for more info at Enable CORS.

4. Broadcasting Messages

After any new employee is created and changes are saved, we notify client about the change.

Fig-#7

We have two types of messages supported by SignalR:-
1. Clients.All — This is used to broadcast message to all clients connected to SignalR server.
2. Clients.Client(ConnectionId) — This is used to broadcast message to specific client based on the connection id passed to it as specified in fig #4.

Fig-#8

5. UI Integration

  • Create a new Angular application using below command.
    ng new SignalR.
  • We can choose the option to create Routing. (By default, it is false)
  • It will take some time to install all the node packages. We can install Signal R Client package using below npm command.
    npm install @microsoft/signalr .
  • Now we can create components and integrate the API to perform CRUD operation. For more info about API integration with Angular we can take reference from Angular-API-Integration.
  • In order to listen to the messages broadcasted by the server, we need establish a connection with SignalR hub connection builder and connection is started. This connection will be listening to the messages from SignalR hub from server. Whenever server sends a message, without refresh all the browsers(i.e. multiple sessions) would be notified with the updated information.
  • We need to add below code to the component’s ngOnInit(), where we want to listen to the broadcasted messages. In my case, I have called in employees.component.ts.

Summary

We learned about how we can use SignalR to provide real-time functionality to our application. Also, we have broadcasted a message to all connected clients from server using SignalR hub.

References

  1. Tutorial: Real-time chat with SignalR 2 | Microsoft Docs

Thanks for reading. Feel free to comment your thoughts about this article below…

--

--