Welcome to our comprehensive guide on ASP.NET Hubs! In this lesson, we'll delve into the world of real-time web functionality using SignalR, a library that enables near-real-time, bidirectional communication between server and clients. This tutorial is designed for both beginners and intermediate learners. Let's get started!
ASP.NET Hubs provide a simple way to add web sockets to your ASP.NET application. Web sockets allow for a persistent connection between the client and the server, enabling real-time communication.
To create an ASP.NET Hub, follow these steps:
Create a new Hub: In your ASP.NET project, create a new item and select "SignalR Hub Class". Name it ChatHub.
Define methods: In the ChatHub class, define methods that will handle client-server communication.
public class ChatHub : Hub
{
public void SendMessage(string user, string message)
{
// Logic to broadcast the message to all clients
}
}Startup.cs file, register the Hub in the Configuration method.public void Configuration(IAppBuilder app)
{
// Other configuration code...
app.MapSignalR();
}To interact with the server, clients must connect to the Hub. In ASP.NET, this can be done using JavaScript or C#.
To create a JavaScript client, include the SignalR library and connect to the Hub.
var connection = new signalR.HubConnectionBuilder()
.withUrl("/chatHub")
.build();
connection.on("ReceiveMessage", function (user, message) {
// Handle incoming messages
});
connection.start().then(function () {
// Send messages to the server
}).catch(function (err) {
console.error(err.toString());
});Let's build a simple real-time chat application using ASP.NET Hubs and SignalR.
SendMessage method in the Hub: This method will broadcast messages to all connected clients.public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}var messageInput = document.getElementById("messageInput");
var chatArea = document.getElementById("chatArea");
connection.on("ReceiveMessage", function (user, message) {
var li = document.createElement("li");
li.textContent = user + ": " + message;
chatArea.appendChild(li);
});
connection.onclose(function (error) {
console.error(error);
});
function sendMessage() {
var user = document.getElementById("user").value;
var message = messageInput.value;
connection.invoke("SendMessage", user, message).catch(function (err) {
console.error(err.toString());
});
messageInput.value = "";
}Now, you have a simple real-time chat application! 🎉
What is the primary purpose of ASP.NET Hubs?