SignalR is a library for ASP.NET that enables real-time web functionality, allowing servers to push updates to clients instantly, enhancing efficiency and responsiveness in applications. It's useful for instant updates in chat apps, live dashboards, and collaborative tools by simplifying communication and supporting various transport protocols. Real-time communication boosts user engagement, reduces resource-intensive polling, and is essential for interactive applications like online gaming and financial trading platforms, providing seamless and dynamic user experiences.
This article will show you how to build a real-time chat application with .Net Core 7 and SignalR.
What is SignalR?
SignalR is a library for ASP.NET that enables real-time web functionality. SignalR uses WebSockets to establish persistent connections between the server and the client, if available. If WebSockets are not available, SignalR relies on other suitable transport protocols such as Server-Sent Events or Long Polling to ensure broad compatibility.
The foundation of SignalR's functionality is based on "Hubs", which are high-level pipeline APIs that enable the server to call methods on connected clients and vice versa. Developers create Hub classes, which contain methods that may be invoked by clients. The client then calls these methods with JavaScript, and SignalR handles the communication details.
SignalR supports grouping connections, which allows messages to be sent to a specific subset of connected clients. This is useful for scenarios like chat rooms, where only certain users should receive specific messages.
SignalR controls connection lifecycles and automatically handles reconnections when a connection is lost. This ensures that the server and clients communicate reliably without forcing the developer to do anything extra.
The server can automatically push updates to clients using the technique provided by SignalR. Because of this, clients may communicate in real-time more effectively and the server burden is decreased without having to query the server for updates.
Steps to create a Real-Time Chat Application with .NET Core 7 and SignalR
Step 1: Setting up the project
Let's start by making a new ASP.NET Core 7 project. In Visual Studio, choose "Create a new project" after opening. Give the project a name and select "ASP.NET Core Web Application" as the project type.
Next, choose the project template "Web Application" and ensure that "Enable Docker Support" is not checked. To begin creating the project, click "Create".
- Open the "Program.cs" file after the project has been created, then add the following code to add SignalR:
builder.Services.AddSignalR();
builder.Services.AddControllersWithViews();
Now Add the SignalR client library to our Project.
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 and signalr.min.js.
- Set Target Location to wwwroot/js/signalr/.
- Select Install.
Step 2: Creating the Hub
- Create a folder named Hubs.
- To create a new folder right click on solution,then click on Add and now click on Add Folder.(Add>Add Folder).
- Rename this newly created to Hubs.
- Every real-time communication between the client and the server will be managed through the Hub. In our project's "Hubs" folder, let's build a new class named "ChatHub".
flood class with below code:
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
namespace YourProjectName.Hubs
{
public class ChatHub : Hub
{
public async Task Message(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
//this will be listen by client using javascript.
}
}
}
This will create a new Hub class inherited from SignalR Hub .We define method named Message,that takes two string parameters user and message , and SendAsync method send messages to all the connected clients.
However ,Before using ChatHub ,we have to Configure It in Program.cs
//...
app.MapHub<ChatHub>("chatHub");
//...
Note: This line configures the SignalR middleware to use the Chat Hub by mapping the "/chatHub" URL to the ChatHub class.
Step 3: Creating UI
- After implementing the Chat Hub, we still need to design the user interface (UI) for our chat program. For real-time communication in this tutorial, a basic HTML page with some JavaScript code will be used.
Add the following code to your project's "index.cshtml" file:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>
SignalR Chat
</title>
<script src=
"https://code.jquery.com/jquery-3.6.0.min.js">
</script>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/5.0.13/signalr.min.js">
</script>
</head>
<body>
<div>
<input id="username" placeholder="username"
type="text" />
<input id="message" placeholder="message"
type="text" />
<button id="send-btn">
Send
</button>
</div>
<div id="chatBox">
</div>
<script>
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chatHub").build();
connection.on("ReceiveMessage", function (User, Message) {
let encodedUser = $("<div />").text(user).html();
let encodedMsg = $("<div />").text(message).html();
$("#chatBox").append("<p><strong>" + encodedUser + "</strong>: " + encodedMsg + "</p>");
});
$("#send-btn").click(function () {
let our_user = $("#username").val();
let Message = $("#message").val();
connection.invoke("Message", our_user, Message);
$("#message").val("").focus();
});
connection.start().then(function () {
console.log("Connected!");
}).catch(function (err) {
console.error(err.toString());
});
</script>
</body>
</html>
Note: This code generates a simple user interface (UI) containing a "Send" button, an input form for the message, and a field for the user's name. Additionally, a div with the id "chatBox" is created, and this is where the chat messages will be shown.
Using the URL "/chatHub" (which we mapped to our ChatHub class in the "Startup.cs" file), we establish a new SignalR connection in the JavaScript code. The "ReceiveMessage" event, which is triggered each time a message is sent from the server to the client, is then handled by a function that we define. The message is appended to the chatBox div using this function.
Additionally, we construct a click event handler for the "Send" button that sends the user's name and message to the server using the "Message" method. Lastly, we initiate the SignalR connection and, upon connection establishment, log a message to the console.
Step 4: Running the application
- Now is the time to start the application To launch the program in debug mode, press F5. You should be able to view the chat UI with the input fields and the "Send" button as soon as the application launches.
- After putting in your name and a message, click "Send". Your message will pop up in the chat window. Navigate to the same URL in an other browser window. Send a message and enter a different name. The message appears in both windows.
Congratulations, you've just built a real-time chat application with .NET Core 7 and SignalR!
Conclusion
This article demonstrates how to use SignalR and.NET Core 7 to create a real-time chat application. The fundamentals of project setup, Chat Hub creation, and Chat UI creation have all been addressed. We hope that this article has given you a better understanding of SignalR's capabilities and how to use them to create real-time web applications. Have fun with coding!
Top comments (0)