Introduction
SignalR is an open source library that adds real-time web functionality to applications. It means, it enables the server-side to push the content to the client instantly rather than the server having to wait for clients to request new data. It provides an API for creating server to client RPC (remote procedure calls). The RPC call JavaScript functions on the client from the server side in .net core code.
SignalR can be used for,
- Applications that require high frequency updates from the server such as social networking, voting ect.
- Applications that require notifications such as email, games, etc.
- Dashboards and monitoring applications
SignalR has been rewritten for ASP.net core 2.1. It includes following improvements,
- No JQuery dependency
- Support custom protocols
- A new compact binary protocol based on MessagePack
- Streaming response model
- Simplified scale-out model
- WebSockets support
Following are some features of SignalR,
- It handles connection management automatically
- Able to send the message to all connected client simultaneously
- Able to send the message to specific client or groups of client
- Scales in/out automatically to handle traffic
SignalR supports many techniques for handling real-time communications such as Web Sockets, Server-Sent Events, and Long Polling. It automatically selecs the best transport method which is suitable for both server and client.
Hubs
The Hubs are used to communicate between server and client in SignalR. It is a high level pipeline that allows the client and server to call methods on each other. SignalR automatically handles the dispatching across machine boundaries that allows the server to call methods on the client and vice versa.
SignalR provides two built-in hub protocols
- Text protocol (based on JSON)
- Binary Protocol (based on MessagePack)
MessagePack creates smaller messages than JSON. Older browsers must support XHR level2 to provide support to MessagePack.
Hubs call client side method by sending the messages which contain the name of the method and its parameter. This method parameter is deserialized using the configured protocol. If the client matches the name of method it calls the method and pass the deserialized parameter data.
Get started with SignalR
In this example, I have create a simple Chat application.
The following software is installed to develop applications with SignalR on ASP.net core
First step is to to create the web application. The web application can be created by using either Visual Studio or CLI.
We can acheive the same thing using CLI by using the following command.
Next step is to download SingleR module using node package manager.
- npm init -y
- npm install @aspnet/signalr
Next step is to copy signalr.js file from "node_modules\@aspnet\signalr\dist\browser" to appropriate folder of our project. In this demo I have created folder "singler" under inside the wwwroot/lib folder and paste this file.
Do not forget to include signalr.js file into script tag.
Create SignalR Hub
The SignalR hub is a class that inherits from Microsoft.AspNetCore.SignalR.Hub. In this class, we can create a method that can be accessed from JavaScript. To send messages to all clients, I have created "SendMessage" method and within this method, I have called the "RecieveMessage" method of the connected client.
- using Microsoft.AspNetCore.SignalR;
- using System.Threading.Tasks;
- namespace ChatApp
- {
- public class ChatHub : Hub
- {
- public async Task SendMessage(string user, string message)
- {
- await Clients.All.SendAsync("ReceiveMessage", user, message);
- }
- }
- }
Next is to configure our project that handles the SignalR Request. To configure SignalR in our project, we need to add signalR service to ConfigureService method of startup class.
- public void ConfigureServices(IServiceCollection services)
- {
- ....
- ....
- services.AddMvc();
- services.AddSignalR();
- }
Also, we need to configure the route to SignalR hubs using UseSignalR method defined in the configure method of startup class. This method(app.UseSignalR) adds SignalR to a middleware pipeline.
- public void Configure(IApplicationBuilder app)
- {
- ...
- ...
- app.UseSignalR(routes =>
- {
- routes.MapHub<ChatHub>("/chatHub");
- });
-
- app.UseMvc();
- }
Using following JavaScript code, we can call the server method "SendMessage" and also we have register ReceiveMessage method, that can be called from server to send send the message to client. This code is written for modern ECMAScript 6, so this code will not work with IE 11 or the other browser that does not support ECMAScript 6.
In this demo, I have created chat.js file under "wwwroot/js" folder.
- const connection = new signalR.HubConnectionBuilder()
- .withUrl("/chatHub")
- .build();
-
-
- connection.on("ReceiveMessage", (user, message) => {
- const msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
- const encodedMsg = user + " :: " + msg;
- const li = document.createElement("li");
- li.textContent = encodedMsg;
- document.getElementById("messagesList").appendChild(li);
- });
-
- connection.start().catch(err => console.error(err.toString()));
-
-
-
- document.getElementById("sendMessage").addEventListener("click", event => {
- const user = document.getElementById("userName").value;
- const message = document.getElementById("userMessage").value;
- connection.invoke("SendMessage", user, message).catch(err => console.error(err.toString()));
- event.preventDefault();
- });
For demo purposes, I have replaced the following content in Pages\index.cshtml file.
- @page
- <div class="container">
- <div class="row"> </div>
- <div class="row">
- <div class="col-md-12">
- <div class="col-md-6">
- <div class="col-md-3">User</div>
- <div class="col-md-9"><input type="text" id="userName" /></div>
- </div>
- </div>
- <div class="col-md-12">
- <div class="col-md-6">
- <div class="col-md-3">Message</div>
- <div class="col-md-9">
- <input type="text" id="userMessage" />
- <input type="button" id="sendMessage" value="Send Message" />
- </div>
- </div>
- </div>
- </div>
- <div class="row">
- <div class="col-12">
- <hr />
- </div>
- </div>
- <div class="row">
- <div class="col-6"> </div>
- <div class="col-6">
- <ul id="messagesList"></ul>
- </div>
- </div>
- </div>
- <script src="~/lib/signalr/signalr.js"></script>
- <script src="~/js/chat.js"></script>
Output
You can view or download the source code from the GitHub link
here.