December 21, 2019
In modern web applications, providing real-time communication can significantly enhance the user experience. Whether it’s live notifications, chat messages, or real-time updates, SignalR allows developers to easily implement real-time web functionality. If you’ve ever wanted to build a live chat application, or any system that requires live data updates, then SignalR in .NET Core is the tool for you.
In this post, we’ll introduce SignalR in .NET Core, discuss what it is, how to implement it, and walk through building a simple real-time chat application.
What is SignalR?
SignalR is a library for ASP.NET Core that simplifies the process of adding real-time web functionality to applications. It allows server-side code to push content to connected clients instantly, without the need for clients to constantly poll the server for updates.
The primary goal of SignalR is to provide real-time, bidirectional communication between the server and client. This makes it ideal for scenarios such as:
- Live chat applications
- Real-time notifications
- Collaborative editing
- Real-time dashboards
SignalR works by managing connections between clients and the server, and it can fall back to different transport mechanisms (WebSockets, Server-Sent Events, Long Polling) depending on what is supported by the client’s browser and the server.
How SignalR Works
SignalR enables server-side code to call methods on client-side code, and client-side code can call methods on the server. When a client establishes a connection to the SignalR hub, it gets a unique connection ID. This allows the server to target specific clients or groups of clients to send messages.
SignalR manages the communication and handles connection management, ensuring a seamless experience for both the client and server.
Setting Up SignalR in .NET Core
Step 1: Install SignalR NuGet Package
To get started, we need to install the SignalR package for .NET Core. You can do this by running the following command in your terminal:
dotnet add package Microsoft.AspNetCore.SignalR
This package contains everything you need to add SignalR functionality to your .NET Core application.
Step 2: Create a SignalR Hub
A Hub is the core concept in SignalR. It acts as a central point where the server can push messages to connected clients. Let’s create a simple hub for our chat application.
In the ChatHub.cs file, define the SignalR hub like this:
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
// Send the message to all connected clients
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
In this example:
- ChatHub inherits from Hub, which is the base class provided by SignalR for managing real-time connections.
- The
SendMessage
method will be called from the client when a user sends a message. This method sends the message to all connected clients usingClients.All.SendAsync
.
Step 3: Configure SignalR in Startup.cs
To use SignalR, you need to configure it in the Startup.cs file by adding it to the services and the HTTP request pipeline.
In the ConfigureServices
method, add SignalR services:
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR();
}
In the Configure
method, map the SignalR hub to an endpoint:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
// Map the SignalR Hub to an endpoint
endpoints.MapHub<ChatHub>("/chatHub");
});
}
This sets up the SignalR ChatHub to be accessible at the /chatHub
endpoint.
Step 4: Create a Simple Chat Client
Now let’s create a simple HTML client to connect to the ChatHub and send/receive messages.
In your wwwroot/index.html file, add the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SignalR Chat</title>
<script src="https://cdn.jsdelivr.net/npm/@microsoft/signalr@3.1.4/dist/browser/signalr.min.js"></script>
</head>
<body>
<h1>SignalR Chat</h1>
<input type="text" id="userInput" placeholder="Enter your name" />
<textarea id="messageInput" placeholder="Enter your message"></textarea>
<button onclick="sendMessage()">Send</button>
<h2>Messages</h2>
<ul id="messagesList"></ul>
<script>
const connection = new signalR.HubConnectionBuilder()
.withUrl("/chatHub")
.build();
// Start the connection
connection.start().catch(err => console.error(err));
// Listen for incoming messages
connection.on("ReceiveMessage", (user, message) => {
const li = document.createElement("li");
li.textContent = `${user}: ${message}`;
document.getElementById("messagesList").appendChild(li);
});
// Send message to server
function sendMessage() {
const user = document.getElementById("userInput").value;
const message = document.getElementById("messageInput").value;
connection.invoke("SendMessage", user, message).catch(err => console.error(err));
}
</script>
</body>
</html>
In this HTML:
- We include the SignalR client library using the CDN.
- We create an input field for the user to enter their name and a textarea for their message.
- We set up the SignalR connection to the
/chatHub
endpoint. - When the user sends a message, the
SendMessage
method is called on the SignalR server, and the message is broadcast to all connected clients.
Step 5: Running the Application
Now that we’ve set up the server and the client, run the application using:
dotnet run
Navigate to http://localhost:5000
in your browser, and you should see the chat interface. Open multiple browser tabs, and messages sent from one tab will be broadcasted to all other connected clients in real-time.
Conclusion
In this post, we introduced SignalR in .NET Core and built a simple real-time chat application. By using SignalR, we can easily add real-time functionality to our applications, enabling features like live notifications, chats, and updates.
You can expand this basic example into more advanced applications, such as live monitoring dashboards, collaborative tools, or multiplayer games.
SignalR makes it simple to implement real-time communication, and with .NET Core, you can build fast, scalable applications that serve users across multiple platforms. In future posts, we’ll explore more advanced SignalR topics, including handling user groups, message broadcasting, and scaling SignalR applications.