Real-Time Chat App with SignalR and .NET MAUI
One of the key features of real-time apps is their ability to provide immediate feedback to users. Examples of such apps include messaging apps, video conferencing apps, collaborative editing tools, and live data dashboards.
One of the most popular examples of a real-time app is a chat app, which allows users to exchange messages in real-time.
Real-time apps are typically built using specialized technologies that allow communication between clients and servers like SignalR.
What is SignalR?
SignalR is an open-source project by Microsoft that enables real-time, two-way web communication from server to clients. Using SignalR, you can write server-side code that pushes content to connected clients instantly.
SignalR handles connection management automatically, and lets you broadcast messages to all connected clients simultaneously, like a chat room.
Setup
To create a real-time chat app using SignalR, let’s begin with creating new ASP.NET Core Web App project.
In your Visual Studio, create a new project:
Add the SignalR client library
In Solution Explorer, right-click the project, and select Add > Client-Side Library.
In the Add Client-Side Library dialog:
- Select unpkg for Provider
- Enter
@microsoft/signalr@latest
for Library. - Select Choose specific files, expand the dist/browser folder, and select
signalr.js
andsignalr.min.js
. - Set Target Location to
wwwroot/js/signalr/
. - Select Install.
Create a SignalR hub
A hub is a class that serves as a high-level pipeline where connected clients subscribes, listens, and sends messages/data.
In the project folder, create a Hubs
folder.
In the Hubs
folder, create the ChatHub
class with the following code:
using Microsoft.AspNetCore.SignalR;
namespace SignalRChatDemo.Hubs
{
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
}
The ChatHub
class inherits from the SignalR Hub class. The Hub
class manages connections, groups, and messaging.
The SendMessage
method handles all of the sent messages which will then send the message to anyone who’s actively listening to ReceiveMessage
.
Configure SignalR
The SignalR server must be configured to pass SignalR requests to SignalR. Add the following code to the Program.cs
file:
builder.Services.AddSignalR();
app.MapHub<ChatHub>("/chatHub");
The above code adds SignalR to the ASP.NET Core dependency injection and routing systems.
Your Program.cs
file should look like this:
using SignalRChatDemo.Hubs;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddSignalR();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.MapHub<ChatHub>("/chatHub");
app.Run();
Run the app
You can run it on your local machine; however, it can only be accessed locally on your computer. To make it accessible to the public, you need to deploy it to Azure or any web server that’s accessible over the internet.
I would recommend using ngrok
to expose your local development server to the internet for debugging and testing purposes. More details and steps to setup here.
Add SignalR client code
Create a .NET MAUI project in Visual Studio and install the NuGet package Microsoft.AspNetCore.SignalR.Client
After the installation, you can configure the hub connection by setting up the URL to which it will connect:
HubConnection hubConnection = new HubConnectionBuilder()
.WithUrl($"https://yoururlhere.com/chatHub")
.Build();
Once done with the configuration, you can start listening to the hub by starting the connection:
async Task Connect()
{
await hubConnection.StartAsync();
}
You can also disconnect to stop the app from listening to it:
async Task Disconnect()
{
await hubConnection.StopAsync();
}
Now, you can start sending and receiving messages.
Sending Messages to the Hub
You can send messages through InvokeAsync
method:
async Task SendMessage(string user, string message)
{
await hubConnection.InvokeAsync("SendMessage", user, message);
}
InvokeAsync
method is used to invoke SendMessage
method on the SignalR hub and passing in two data, the name of the user and the text message.
Receiving Messages from the Hub
To receive messages from the hub, make sure your app is actively listening to ReceiveMessage
.
Set up a callback function that is triggered when a message is received from the SignalR hub:
hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
{
// do something here..
});
Here’s a quick demo of running application on Android emulator and Windows machine:
That’s all you need to build a real-time chat app with SignalR and .NET MAUI!
Closing thoughts
This post only scratches the surface of the SignalR and the possibilities it offers in building real-time chat apps with .NET MAUI. While we covered some of the fundamental concepts, there is much more to explore and learn! To create a robust and feature-rich chat application, you will need to dive deeper into SignalR and its related technologies, such as WebSocket, Azure SignalR Service, and more.
Try it on your own! Here’s the source code for the hub and the client app.