SignalR – Real Time Communication

Spread the love

Introduction To SignalR

 Now in this article, we will see the implementation of SignalR with .NET core

Software’s requires to develop an application with SignalR on ASP.NET Core

  • Node package manager(npm) – https://www.npmjs.com/get-npm
  • .NET Core SDK 2.1 or later -https://www.microsoft.com/net/download/archives
  • Visual Studio 2017 (Version 15.7.3 or later)

Let’s create simple communication application using SignalR with ASP.NET Core

  • File – New – Project – Create New web application.

  • Then select Web Application.

  • Next step is to download a SignalR module using a node package manager.

    • npm init -y
    • npm install @aspnet/signalr
  • Copy signalr.js file from node installed location and copy in our project.
  • Do not forget to include signalr.js file into your HTML Page script tag.

Create SignaR Hub

  • Now to create a SignalR hub, a signalR hub is a class that inherits from Microsoft.ASpNetCore.SignalR.Hub.

  • Let’s create a method that can be accessed from JavaScript.

  • To send the message to all clients, I have created “SendMessage” method and within this method, I will call the “ReceiveMessage” method of the connected client.
  1. using Microsoft.AspNetCore.SignalR;  
    1. using System.Threading.Tasks;  
    1. namespace CommunicationApp  
    1. {  
    1.     public class ChatHub : Hub  
    1.     {  
    1.         public async Task SendMessage(string user, string message)  
    1.         {  
    1.             await Clients.All.SendAsync(“ReceiveMessage”, user, message);  
    1.         }  
    1.     }  
    1. }  
  • Next step is that we need to configure our project to handle the SignalR Request.
  • So to configure SignalR in our project, we need to add signalR service to ConfigureService method of startup class.
  1. publicvoid ConfigureServices(IServiceCollection services)  
    1. {  
    1.     ….  
    1.     ….  
    1.     services.AddSignalR();  
    1. }  
  • Also we need to configure the route to signalR hubs using UseSignalR method defined in configure method of startup class.

  • This method(app.UseSignalR) adds SignalR to a middleware pipeline.
  1. publicvoid Configure(IApplicationBuilder app)  
    1. {  
    1.     …  
    1.     …  
    1.     app.UseSignalR(routes =>  
    1.     {  
    1.            routes.MapHub<ChatHub>(“/chatHub”);  
    1.      });  
    1.   
    1.      app.UseMvc();  
    1. }  
  • So by using JavaScript code, we call the server method called “SendMessage” and also we have registered ReceiveMessage method, which is usually called from the server to send the message to the client.

  • Just create chat.js file under “wwwroot/js” folder.
  1. const connection = new signalR.HubConnectionBuilder()  
    1.     .withUrl(“/chatHub”)  
    1.     .build();  
    1.   
    1. //This method receive the message and Append to our list  
    1. connection.on(“ReceiveMessage”, (user, message) => {  
    1.     const msg = message.replace(/&/g, “&”).replace(/</g, “<“).replace(/>/g, “>”);  
    1.     const encodedMsg = user + ” :: ” + msg;  
    1.     const li = document.createElement(“li”);  
    1.     li.textContent = encodedMsg;  
    1.     document.getElementById(“messagesList”).appendChild(li);  
    1. });  
    1.   
    1. connection.start().catch(err => console.error(err.toString()));  
    1.   
    1. //Send the message  
    1.   
    1. document.getElementById(“sendMessage”).addEventListener(“click”, event => {  
    1.     const user = document.getElementById(“userName”).value;  
    1.     const message = document.getElementById(“userMessage”).value;  
    1.     connection.invoke(“SendMessage”, user, message).catch(err => console.error(err.toString()));  
    1.     event.preventDefault();  
    1. });   
  • Now replace the following code content in page\index.cshtml file.
  1. @page  
    1. <div class=”container”>  
    1.     <div class=”row”> </div>  
    1.     <div class=”row”>  
    1.         <div class=”col-md-12″>  
    1.             <div class=”col-md-6″>  
    1.                 <div class=”col-md-3″>User</div>  
    1.                 <div class=”col-md-9″><input type=”text” id=”userName” /></div>  
    1.             </div>  
    1.         </div>  
    1.         <div class=”col-md-12″>  
    1.             <div class=”col-md-6″>  
    1.                 <div class=”col-md-3″>Message</div>  
    1.                 <div class=”col-md-9″>  
    1.                     <input type=”text” id=”userMessage” />      
    1.                     <input type=”button” id=”sendMessage” value=”Send Message” />  
    1.                 </div>  
    1.             </div>  
    1.         </div>  
    1.     </div>  
    1.     <div class=”row”>  
    1.         <div class=”col-12″>  
    1.             <hr />  
    1.         </div>  
    1.     </div>  
    1.     <div class=”row”>  
    1.         <div class=”col-6″> </div>  
    1.         <div class=”col-6″>  
    1.             <ul id=”messagesList”></ul>  
    1.         </div>  
    1.     </div>  
    1. </div>  
    1. <script src=”~/lib/signalr/signalr.js”></script>  
    1. <script src=”~/js/chat.js”></script>  

Leave a Comment

Your email address will not be published. Required fields are marked *

https://www.cooljerseyedge.com, https://www.collegeshopfan.com, https://www.kcchiefsgearusa.com, https://www.dlionsgearusa.com, https://www.bravensgearusa.com, https://www.cbengalsgearusa.com, https://www.gbpackersgearusa.com, https://www.htexansgearusa.com, https://www.laramsgearusa.com, Josh Allen Wyoming Jersey, https://www.dcowboysgearusa.com, https://www.mdolphinsgearusa.com, https://www.aliexfanshop.com, https://www.bestplayershop.com, https://www.collegeedgeshop.com, https://www.giantsonlinefans.com