SignalR is a C# library that provides the functionality to receive real-time updates from the server triggered by an event on the server and not by a client's request.
To set up a .NET console app, we need .NET 6 and a code editor compatible with C#. After setting up the environment, we must create a .NET project. To create the project, go to an appropriate directory in our file system and create a folder named LearningSignalR
.
Navigate to the created folder in a terminal. Inside the folder, execute the following command:
dotnet new sln
If the command's execution doesn't run through any error, it should create a file named LearningSignalR.sln
. Now, create a project based on ASP.NET. To do so, execute the following command in the same folder:
donet new mvc -o SignalRServer
It creates a SignalRServer
folder in the solution folder.
Now, to add the SignalRServer
project to the solution, run the following command:
dotnet sln add SignalRServer/SignalRServer.csproj
We've created an ASP.NET project. Now, we're ready to add SignalR to our project. Firstly, we must set up the SignalR hub. For this, navigate to the SignalRServer
project folder. The folder's hierarchy is as follows:
Add a new folder and name it Hubs
. Inside the folder, create a LearningHub.cs
file and populate the file with the following code:
using Microsoft.AspNetCore.SignalR;namespace SignalRServer.Hubs{public class LearningHub : Hub{public async Task BroadcastMessage(string message){await Clients.All.SendAsync("ReceiveMessage", message);}public override async Task OnConnectedAsync(){await base.OnConnectedAsync();}public override async Task OnDisconnectedAsync(Exception? exception){await base.OnDisconnectedAsync(exception);}}}
To enable SignalR and use it in the project, add the following lines to the Program.cs
file:
using SignalRServer.Hubs;builder.Services.AddSignalR();app.MapHub<LearningHub>("/learningHub");
using
statement.Free Resources