How to Build your Real-Time Apps with SignalR?
Real-time apps are programs that work within a timeframe and show current updated value to all the users. For eg: we have Stock exchange, Commodities, Live score of any match, weather, COVID19 count, Statistics, Dashboards etc. All the users can see the latest value even if they have interacted with it or not. The latency should be less than a define value in seconds. Information of data is sent and received in milliseconds.
What is SignalR?
SignalR is an open-source software library for Microsoft ASP.NET . It allows server code to send asynchronous notifications to client-side web applications. Asp.net SignalR is a library for Asp.net Developers to add real-time web functionalities to their applications. These functionalities are kind of ability to have server side code push content to connected clients.
For most applications, we recommend SignalR over raw WebSockets. SignalR provides transport fallback for environments where WebSockets is not available. It also provides a simple remote procedure call app model. And in most scenarios, SignalR has no significant performance disadvantage compared to using raw WebSockets. It takes advantage of WebSocket, an HTML5 API that enables bi-directional communication between the browser and server. SignalR also provides a high-level API for doing server-to-client RPC (Remote procedure Call). It calls JavaScript functions in a client’s browser from server-side .NET Core/MVC code. It also adds useful hooks for connection management, such as connect/disconnect events, grouping connections, authorization.
Where to use SignalR?
- Apps that require high frequency updates from the server. Examples are gaming, social networks, voting, auction, maps, and GPS apps.
- Dashboards and monitoring apps. Examples include company dashboards, instant sales updates, or travel alerts.
- Collaborative apps. Whiteboard apps and team meeting software like JIRA, Trello are examples of collaborative apps.
- Apps that require notifications. Social networks like Facebook, Instagram etc., email, chat, games, travel alerts, and many other apps use notifications.
Transports
SignalR supports the following techniques for handling real-time communication
- WebSockets
- Server-Sent Events
- Long Polling
SignalR automatically chooses the best transport method that is within the capabilities of the server and client. It works with Asp.net 4.5, Asp.Net MVC as well as .Net Core. Here we will like to talk about SignalR with Asp.Net Core.
What is WebSocket?
Websocket is a communications protocol, providing full-duplex communication channels over a single TCP connection. The WebSocket API is an advanced technology that makes it possible to open a two-way interactive communication session between the user’s browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply. It is basically a live connection between server and client.
SignalR is an abstraction over some of the transports that are required to do real-time work between client and server. A SignalR connection starts as HTTP, and is then promoted to a WebSocket connection if it is available.
Features
- Handles connection management automatically.
- Sends messages to all connected clients simultaneously. For example, a chat room.
- Sends messages to specific clients or groups of clients.
- Scales to handle increasing traffic.
Configure the middleware
The SignalR server must be configured to pass SignalR requests.
public void ConfigureServices(IServiceCollection services) { services.AddSignalR(); } |
Add the WebSockets middleware in the Configure method of the Startup class in Dotnet Core:
app.UseWebSockets(); // Accept WebSocket requests app.Use(async (context, next) => { if (context.Request.Path == “/ws”) { if (context.WebSockets.IsWebSocketRequest) { WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(); await Echo(context, webSocket); } else { context.Response.StatusCode = 400; } } else { await next(); } }); |
A WebSocket request could come in on any URL, but this sample code only accepts requests for ‘/ws’.
Hubs
A hub is a high-level pipeline that allows a client and server to call methods on each other. SignalR handles the dispatching across machine boundaries automatically, allowing clients to call methods on the server and vice versa. You can pass strongly-typed parameters to methods, which enables model binding. SignalR provides two built-in hub protocols: a text protocol based on JSON and a binary protocol based on MessagePack. MessagePack generally creates smaller messages compared to JSON.
The SignalR Hubs API enables you to call methods on connected clients from the server. In the server code, you define methods that are called by the client. In the client code, you define methods that are called from the server. SignalR takes care of everything behind the scenes that makes real-time client-to-server and server-to-client communications possible.
Configure SignalR Hubs
The SignalR middleware requires some services, which are configured by calling services.AddSignalR.
//SignalR Routes app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapHub<MyHub>(“/myhub”); });
//Using Hub public class ChatHub : Hub { public Task SendMessage(string user, string message) { return Clients.All.SendAsync(“ReceiveResponse”, user, message); } } |
Create a hub by declaring a class that inherits from Hub, and add public methods to it. Clients can call methods that are defined as public. You can specify a return type and parameters, including complex types and arrays, as you would in any C# method. SignalR handles the serialization and deserialization of complex objects and arrays in your parameters and return values.
Send response to clients
- SendMessage sends a message to all connected clients, using Clients.All.
- SendMessageToCaller sends a message back to the caller, using Clients.Caller.
- SendMessageToGroups sends a message to all clients in the SignalR Users group.
public Task SendMessage(string user, string message) { return Clients.All.SendAsync(“ReceiveResponse”, user, message); }
public Task SendMessageToCaller(string message) { return Clients.Caller.SendAsync(“ReceiveResponse “, message); }
public Task SendMessageToGroup(string message) { return Clients.Group(“SignalR Users”).SendAsync(“ReceiveResponse “, message); }
|
SignalR with Angular
Now the question is how to call these methods from the client side, so we have some JavaScript libraries and NPM packages for SignalR where we are connected with server Hub and can send messages as per application flow. If we want to implement into Angular then bellow code is to install package:
npm install @aspnet/signalr |
As per below image all clients are connected to single SignalR Hub, Hub will send the response whenever any event occurs, this is a real time process so client will watch for the response, when hub send the message then all clients can receive it, hub can send to particular client, in Group or to All clients as per previous discussion.
//Create a connection let connection = new signalR.HubConnectionBuilder() .withUrl(“/chat”) .build();
//Start connection connection.start() .then(() => { . . . }); //Invoke/Send message to SignalR Hub connection.invoke(“send”, “Hello”)
//Receive response from SignalR Hub connection.on(“send”, data => { console.log(data); }); |
This way we have tried to demonstrate how you can build your Real-Time application using SignalR along with Angular & Asp.net Core.
We recently built a Realtime Chat, social timeline feed and a Live Auction System for multiple clients from US & Australia using the above technology stack combination.
In case you have similar or any other Realtime requirement, you can always consult with us at shalin@ncoresoft.com or
Skype : shalin.jirawla