SignalR 101: A Beginner’s Guide to Real-time Web Communication in .NET 6 (2024)

Justin Muench

·

Follow

--

SignalR 101: A Beginner’s Guide to Real-time Web Communication in.NET 6 (2)

Real-time web communication has become a vital aspect of modern web development. It enables web apps to receive and send data in real time, providing a more responsive and interactive user experience.

SignalR is a library for .NET that makes it easy to add real-time functionality to your web apps. In this post, we will explore the fundamentals of SignalR in .NET 6 and how to implement it in a web application.

We will start by setting up a new SignalR project in .NET 6 and go over the basic structure of a SignalR project. Then, we’ll dive into sending and receiving messages between the client and the server.

After reading this post, you will understand how to implement real-time web communication in your .NET 6 projects using SignalR.

Real-time web communication refers to the ability of web apps to send and receive data in real time without needing a page refresh. This allows for a more interactive and responsive user experience. An example of real-time web communication is a chat application where messages are sent and received instantly between users without the need to refresh the page. Another example could be a live-tracking system where the updates on the map are in real time.

SignalR is a library for .NET that makes it easy to add real-time functionality to web apps. It is an open-source library developed by Microsoft that simplifies adding real-time functionality to web apps. SignalR uses WebSockets, Server-Sent Events (SSE) (If WebSockets are not supported), and long polling to establish a real-time connection between the client and the server, allowing for real-time communication without the need for complex coding.

SignalR also supports fallback mechanisms, so it can work on older browsers and networks that don’t support WebSockets. With SignalR, developers can easily add real-time functionality to their web apps, such as notifications, chat systems, and live updates.

In SignalR, the server-side code is organized into “hubs,” which handle client and server communication. A hub is a C# class that inherits from Microsoft.AspNetCore.SignalR.Hub class and contains methods clients can invoke. These methods are known as “hub methods,” which can be called from the client-side code to send data to the server or receive data from the server. Hubs also provide a way for the server to send data to specific clients or groups of clients.

On the other hand, Clients are the web pages or web apps that connect to a hub to send and receive data. Clients can be written in any language that supports web development, such as JavaScript, C#, and Java. Clients use the SignalR library to connect to a hub and invoke its methods. The SignalR library automatically handles the communication with the hub, including fallback mechanisms for older browsers or networks that don’t support WebSockets. Clients can also subscribe to events raised by the hub, allowing them to receive real-time updates from the server.

Enough with the theory to make the whole thing more practical now follows the demo. First, we set up two projects, a server and a client. I created an empty Web API .NET 6 project and a console App. Let’s start with the configuration of the server.

The project can be found:

Let’s begin with creating the hub. I made a new folder called Hubs and a class called MessageHub. Furthermore, I created a class called NotifyMessage, containing some fields.

public class Message
{
public string? Username { get; set; }
public string? Message { get; set; }
public DateTime Timestamp { get; set; }
}
using Medium_example_SIgnalR.Notify;
using Microsoft.AspNetCore.SignalR;

namespace Medium_example_SIgnalR.Hubs;

public class MessageHub : Hub
{
public async Task SendMessage(MessageNotify message)
{
await Clients.All.SendAsync("ReceiveMessage", message);
}
}

await Clients.All.SendAsync("ReceiveMessage", message); - This line of code uses the hub's property, representing all connected clients. The All property is used to send messages to all connected clients. The SendAsync method is used to send the message asynchronously, and it takes twoJavaScript parameters: the first is the name of the function that should be invoked on the client, in this case, "ReceiveMessage," and the second is the data that should be passed to the function, in this case, the message object.

This code sends a message to all connected clients and invokes the function “ReceiveMessage” on the client side, passing the message object as an argument.

In the next step, we must register the hub in the program.cs.

using Medium_Example_SignalR;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors();
builder.Services.AddSignalR();

var app = builder.Build();

app.UseHttpsRedirection();
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());

app.MapHub<MessageHub>("/messagehub");

app.Run();

builder.Services.AddSignalR(); - This line of code is used to add the SignalR services to the Dependency Injection (DI) container. The AddSignalR method is an extension provided by the SignalR package that adds the necessary services to the DI container. These services include the hub pipeline, connection managers, and other components required for SignalR to work.

app.MapHub<MessageHub>("/messagehub"); - This line of code is used to configure the SignalR hub. The MapHub method is an extension provided by the SignalR package that maps the specified hub type to a path. The first parameter is the hub type, in this case, the MessageHub class. The second parameter is the path the hub should be mapped to, in this case, "/messagehub". The class will handle the connection when a client connects to the "/messagehub" path.

So the first line of code adds the SignalR services to the DI container, and the second line defines a path for the hub so the client can connect to it.

Now it should go on with the client. Let’s add a console project.

After adding the project, we need to install the SignalR Client package and open a connection to our hub.

dotnet add package Microsoft.AspNetCore.SignalR.Client
var connection = new HubConnectionBuilder()
.WithUrl("http://localhost:5038/messagehub")
.Build();

The code creates a new instance of the HubConnection class, the client-side component of SignalR that enables communication with a SignalR server. The HubConnectionBuilder class is used to configure the connection, and the Build method is used to build and return the HubConnection instance.

In the code, the WithUrl the method is called to set the URL of the SignalR hub. The URL should point to the path where the SignalR hub is hosted. In this case, the URL is "http://localhost:5038/messagehub", which means the hub is hosted at the local machine (localhost) on port 5038, and the path of the hub is "/messagehub".

Once the HubConnection an instance is created, you can connect to the hub, subscribe to messages, and send messages to the server. This code is just setting up the connection; to use it, you need to call the StartAsync method on the connection variable to start the connection and subscribe to events, etc. As seen below.

try
{
await connection.StartAsync();
Console.WriteLine("Connected to SignalR Hub");

connection.On<NotifyMessage>("ReceiveMessage", (message) =>
{
Console.WriteLine($"{message.Username}: {message.Message}");
});

var notifyMessage = new NotifyMessage
{
Username = "John Doe"
};
while (true)
{
Console.WriteLine("Enter a message to send to the server");
var message = Console.ReadLine();
notifyMessage.Message = message;

await connection.InvokeAsync("SendMessage", notifyMessage);
Console.WriteLine("Message sent");
Console.ReadLine();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

  • The await connection.StartAsync(); the line starts the connection to the SignalR hub.
  • The connection.On<NotifyMessage>("ReceiveMessage", (message) => line registers a handler for the "ReceiveMessage" event that takes an NotifyMessage object as a parameter. The handler writes the message to the console.
  • The var notifyMessage = new NotifyMessage the line creates a new NotifyMessage object with the Username set to "John Doe."
  • The while (true) loop allows the user to enter messages and send them to the server using continuously await connection.InvokeAsync("SendMessage", notifyMessage);. The sent message is then written to the console.
  • In case of an exception, the catch block writes the exception message to the console.

SignalR is not suitable for every type of web application. It is mainly designed for real-time communication and may not be the best choice for applications that don’t require real-time functionality. Additionally, SignalR may not be suitable for applications that run on low-bandwidth or unreliable networks, as real-time communication requires a stable and fast network connection.

Other technologies better suited for offline or low-bandwidth scenarios may be better. Additionally, your application needs to support older browsers or devices that do not have modern web standards. In that case, SignalR may not be compatible, as it relies on WebSockets and other modern web technologies. In such cases, consider alternative solutions.

In conclusion, real-time web communication is essential to modern web applications. It enables developers to create responsive and interactive user experiences and provides an efficient way to push data from the server to the client in real time. SignalR is a powerful library that simplifies adding real-time communication to .NET applications.

Using SignalR, developers can save time and effort in building real-time communication features and ensure compatibility with a wide range of client capabilities. However, it is essential to carefully consider your specific requirements and the limitations of SignalR before deciding to use it in your application.

Whether you are building a real-time chat application, a collaborative workspace, or need to push updates to your users, SignalR provides a convenient solution for adding real-time communication to your .NET application.

SignalR 101: A Beginner’s Guide to Real-time Web Communication in .NET 6 (2024)
Top Articles
Latest Posts
Article information

Author: Rev. Porsche Oberbrunner

Last Updated:

Views: 6027

Rating: 4.2 / 5 (73 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Rev. Porsche Oberbrunner

Birthday: 1994-06-25

Address: Suite 153 582 Lubowitz Walks, Port Alfredoborough, IN 72879-2838

Phone: +128413562823324

Job: IT Strategist

Hobby: Video gaming, Basketball, Web surfing, Book restoration, Jogging, Shooting, Fishing

Introduction: My name is Rev. Porsche Oberbrunner, I am a zany, graceful, talented, witty, determined, shiny, enchanting person who loves writing and wants to share my knowledge and understanding with you.