Overview
Hello friends, SignalR is a concept through which servers and clients communicate instantly without waiting for each other. So in this blog, we will create a real-time chat application using SignalR with Blazor. So, let’s start.
Introduction to SignalR
SignalR is a library for developers that can be used for creating real-time web functionality where clients can get new data without refreshing a web page. Using the SignalR server and the clients can communicate with each other instantly.
The client is hosted in a browser and the server is hosted in our local machine where clients are connected with the server so clients can send and receive data to the server as shown in the above image, the server is SIgnalR Hub and the Clients are hub connections. So the Server can send data to clients and vice-versa.
Requirements for Create Chat app
Visual Studio 2022 or later versions.
.NET 6.0 SDK
Steps to Create Chat Application
- Create a new project in the visual studio 2022.
- Choose Blazor WebAssembly App template and click Next.
- Set a meaningful project name “BlazorSignalRChatApp” and location for project setup and click Next.
- Select .NET 6.0 framework and ASP.NET Core hosted checkbox.
- Click on the Create button.
Install SignalR client library Package
Right-click on the BlazorSignalRChatApp.Client project from Solution Explorer and select Manage NuGet Packages.
Select nuget.org for managing NuGet Package sources.
In the Browse section, type Microsoft.AspNetCore.SignalR.Client and select the stable version and click the install button.
Click on the I Accept button to install the package.
Add SignalR hub
In the BlazorSignalRChatApp.Server project, create Hubs folder and add class ChatHub.cs in that folder.
using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; namespace BlazorSignalRChatApp.Server.Hubs { public class ChatHub : Hub { public async Task ChatMessageSend(string username, string usermessage) { await Clients.All.SendAsync("UserMessageReceive", username, usermessage); } } }
Add services and endpoint for SignalR Hub
Open Program.cs file from BlazorSignalRChatApp.Server project.
In this Program.cs file we need to follow the steps:
- Add Namespaces
- Add SignalR
- Add Response Compression Services
Create chatapphub as the endpoint in program.cs file.
using BlazorSignalRChatApp.Server.Hubs; builder.Services.AddSignalR(); builder.Services.AddResponseCompression(opts => { opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat( new[] { "application/octet-stream" }); }); app.UseResponseCompression(); app.MapHub<ChatHub>("/chatapphub");
Add Razor Component Code for Chat App
From BlazorSignalRChatApp.Client project, open Index.razor page and add the following code to the razor page.
Here we have built the HubConnection property for communicating with “/chatapphub” endpoint. Using “UserMessageReceive” the client constantly listens to messages from the server.
@page "/" @using Microsoft.AspNetCore.SignalR.Client @inject NavigationManager NavManager @implements IAsyncDisposable <PageTitle>Index</PageTitle> <div class="form-group"> <label for="exampleInputEmail1">UserName:</label> <input type="text" class="form-control" @bind="UserName" placeholder="Enter username"> </div> <div class="form-group"> <label for="exampleInputPassword1">Message:</label> <input type="text" class="form-control" @bind="UserMessage" placeholder="Enter text here"> </div> <button @onclick="Send" disabled="@(!IsConnected)" class="mt-2 btn btn-success">Send</button> <hr> <ul id="messagesList"> @foreach (var UserMessages in MessagesList) { <li>@UserMessages</li> } </ul> @code { private HubConnection? hubConnection; private List<string> MessagesList = new List<string>(); private string? UserName; private string? UserMessage; protected override async Task OnInitializedAsync() { hubConnection = new HubConnectionBuilder() .WithUrl(NavManager.ToAbsoluteUri("/chathub")) .Build(); hubConnection.On<string, string>("UserMessageReceive", (username, usermessage) => { var userMsg = $"{username}: {usermessage}"; MessagesList.Add(userMsg); StateHasChanged(); }); await hubConnection.StartAsync(); } private async Task Send() { if (hubConnection is not null) { await hubConnection.SendAsync("SendMessage", UserName, UserMessage); } } public bool IsConnected => hubConnection?.State == HubConnectionState.Connected; public async ValueTask DisposeAsync() { if (hubConnection is not null) { await hubConnection.DisposeAsync(); } } }
Run Project
Select BlazorSignalRChatApp.Server from Solution Explorer and press F5 to run the chat application project.
Output:
So here we can see that Jenny and Julli can communicate with each other and both can get updated data instantly without refreshing a page.
Conclusion
So, this is all about how we can implement SignalR in real-time applications and get updated data without refreshing a web page. Thank you for reading this blog, hope this will be helpful to you.