Zum Fußzeileninhalt springen
.NET HILFE

Signalr C# (Wie es für Entwickler funktioniert)

The modern web thrives on interactivity and real-time feedback. When building responsive applications, real-time web functionality is a must. This is where SignalR shines. ASP.NET Core SignalR is a library that makes adding real-time web functionality to your applications simpler than you might think.

In this tutorial, we'll embark on a journey through the basics and nuances of SignalR. Let’s dive in!

Introduction to SignalR in ASP.NET Core

ASP.NET Core SignalR provides an API for creating real-time web functionality using WebSockets and other technologies, like server-sent events. It's not just limited to ASP.NET Core. You can use SignalR with various clients, like a browser or a mobile app, ensuring connected clients are updated instantly.

Setting Up Your Development Environment

To get started, you’ll need:

Building the SignalR Hub

At its core, SignalR revolves around a SignalR hub, a central point for both the client and the server to interact.

Create a new ASP.NET Core project. Now, add a new class and name it ChatHub. This will act as our SignalR hub.

using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;

// Define a SignalR Hub class named ChatHub
public class ChatHub : Hub
{
    // Asynchronous method to send messages
    public async Task SendMessage(string user, string message)
    {
        // Send a message to all connected clients
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;

// Define a SignalR Hub class named ChatHub
public class ChatHub : Hub
{
    // Asynchronous method to send messages
    public async Task SendMessage(string user, string message)
    {
        // Send a message to all connected clients
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}
Imports Microsoft.AspNetCore.SignalR
Imports System.Threading.Tasks

' Define a SignalR Hub class named ChatHub
Public Class ChatHub
	Inherits Hub

	' Asynchronous method to send messages
	Public Async Function SendMessage(ByVal user As String, ByVal message As String) As Task
		' Send a message to all connected clients
		Await Clients.All.SendAsync("ReceiveMessage", user, message)
	End Function
End Class
$vbLabelText   $csharpLabel

In the Startup class, let's integrate our hub.

public class Startup
{
    // Configure services and add SignalR
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSignalR(); // Add SignalR services
    }

    // Configure the app to use SignalR and map the hub
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // Setup endpoint to route to ChatHub
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapHub<ChatHub>("/chatHub");
        });
    }
}
public class Startup
{
    // Configure services and add SignalR
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSignalR(); // Add SignalR services
    }

    // Configure the app to use SignalR and map the hub
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // Setup endpoint to route to ChatHub
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapHub<ChatHub>("/chatHub");
        });
    }
}
Public Class Startup
	' Configure services and add SignalR
	Public Sub ConfigureServices(ByVal services As IServiceCollection)
		services.AddSignalR() ' Add SignalR services
	End Sub

	' Configure the app to use SignalR and map the hub
	Public Sub Configure(ByVal app As IApplicationBuilder, ByVal env As IWebHostEnvironment)
		' Setup endpoint to route to ChatHub
		app.UseEndpoints(Sub(endpoints)
			endpoints.MapHub(Of ChatHub)("/chatHub")
		End Sub)
	End Sub
End Class
$vbLabelText   $csharpLabel

Client Side Implementation

SignalR is versatile. While this tutorial focuses on the ASP.NET Core and the JavaScript client library, SignalR supports various clients, from .NET to Java.

Using the SignalR Client Library

The SignalR client library lets your client-side code connect and communicate directly with the server side. For our example, let's use JavaScript.

First, add the SignalR JavaScript client library:

<script src="https://cdn.jsdelivr.net/npm/@microsoft/signalr@3.1.8/dist/browser/signalr.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@microsoft/signalr@3.1.8/dist/browser/signalr.js"></script>
HTML

Now, you can connect to the hub:

// Create a connection to the SignalR hub
const connection = new signalR.HubConnectionBuilder()
    .withUrl("/chatHub") // The hub URL
    .build();

// Start the connection
connection.start().catch(err => console.error(err.toString()));

// Setup a listener for receiving messages
connection.on("ReceiveMessage", (user, message) => {
    console.log(`${user} says: ${message}`);
});
// Create a connection to the SignalR hub
const connection = new signalR.HubConnectionBuilder()
    .withUrl("/chatHub") // The hub URL
    .build();

// Start the connection
connection.start().catch(err => console.error(err.toString()));

// Setup a listener for receiving messages
connection.on("ReceiveMessage", (user, message) => {
    console.log(`${user} says: ${message}`);
});
JAVASCRIPT

This simple client-side code connects to the hub and listens for any messages broadcast.

Real-Time Functionality in Action

Sending Messages

Using our earlier client-side and server-side code snippets, sending messages is straightforward. Both the server and the client can initiate communication.

From server-side:

// Send a message from the server to all connected clients
await Clients.All.SendAsync("ReceiveMessage", "Server", "Hello from server!");
// Send a message from the server to all connected clients
await Clients.All.SendAsync("ReceiveMessage", "Server", "Hello from server!");
' Send a message from the server to all connected clients
Await Clients.All.SendAsync("ReceiveMessage", "Server", "Hello from server!")
$vbLabelText   $csharpLabel

And from client:

// Send a message from the client to the server
connection.send("SendMessage", "Client", "Hello from client!")
    .catch(err => console.error(err.toString()));
// Send a message from the client to the server
connection.send("SendMessage", "Client", "Hello from client!")
    .catch(err => console.error(err.toString()));
JAVASCRIPT

Advanced Real-Time Communication

ASP.NET Core SignalR offers advanced real-time communication features:

  1. Grouping Connections: Segment connected clients into groups, broadcasting messages to specific segments.
  2. Handling Disconnections: Automatically manage client connections and disconnections.
  3. Binary Protocol: While SignalR uses a text-based protocol by default, it supports a binary protocol as well.

SignalR with Azure SignalR Service

For scalable real-time functionality, integrate Azure SignalR Service. This fully managed service supports massive numbers of simultaneous connections, making it ideal for high-demand apps.

Integrating Azure SignalR Service:

  1. Install the Azure SignalR SDK.
  2. Use Azure Service Bus for backplane support.
  3. Adjust the Startup class to use Azure SignalR.
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Add Azure SignalR services
        services.AddSignalR().AddAzureSignalR();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // Use Azure SignalR and map hub with routes
        app.UseAzureSignalR(routes =>
        {
            routes.MapHub<ChatHub>("/chatHub");
        });
    }
}
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Add Azure SignalR services
        services.AddSignalR().AddAzureSignalR();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // Use Azure SignalR and map hub with routes
        app.UseAzureSignalR(routes =>
        {
            routes.MapHub<ChatHub>("/chatHub");
        });
    }
}
Public Class Startup
	Public Sub ConfigureServices(ByVal services As IServiceCollection)
		' Add Azure SignalR services
		services.AddSignalR().AddAzureSignalR()
	End Sub

	Public Sub Configure(ByVal app As IApplicationBuilder, ByVal env As IWebHostEnvironment)
		' Use Azure SignalR and map hub with routes
		app.UseAzureSignalR(Sub(routes)
			routes.MapHub(Of ChatHub)("/chatHub")
		End Sub)
	End Sub
End Class
$vbLabelText   $csharpLabel

Iron Suite Enhancing SignalR with Premium .NET Tools

While ASP.NET Core SignalR provides an outstanding foundation for real-time web functionality, developers often look for tools to enhance the overall experience and functionality. That's where Iron Software Suite of Libraries enters the picture.

Iron Suite is a suite of premium .NET libraries, designed to supercharge your ASP.NET Core applications, including those utilizing SignalR. Each product in this suite offers unique capabilities, ensuring a richer application experience. Let's delve into the offerings:

IronPDF

Signalr C# (How It Works For Developers) Figure 1

Learn more about IronPDF capabilities lets you generate, edit, and read PDF files within your .NET applications. Imagine integrating SignalR in a scenario where a team collaborates on a document in real-time. As changes are made, the document can be converted to a PDF on the fly, with updates pushed to all connected clients seamlessly. The real-time functionality of SignalR paired with IronPDF's capabilities could revolutionize collaborative tools.

IronPDF converts HTML, URLs, and full webpages into stunning PDFs like the original. It’s perfect for saving online reports, invoices, or any web-based information you want to keep. Are you looking to turn HTML to PDF? Try IronPDF today!

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

IronXL

Signalr C# (How It Works For Developers) Figure 2

When it comes to working with Excel spreadsheets, Explore IronXL Features is a champion. In a business setting, spreadsheets play a vital role. Incorporating SignalR alongside IronXL means that financial teams could work on budget sheets in real-time, witnessing changes as they happen. Imagine a scenario where data entries from various departments flow into a centralized Excel sheet, with real-time updates for all stakeholders. The fusion of real-time communication and dynamic spreadsheet management becomes a reality with this combination.

IronOCR

Signalr C# (How It Works For Developers) Figure 3

Optical Character Recognition (OCR) has become a staple in modern applications. See IronOCR in action empowers .NET developers to extract text from images and documents. Pairing this with SignalR's real-time functionality can be game-changing. Consider a platform where users upload images containing textual data. SignalR could be used to notify users in real-time once IronOCR processes the images, making data extraction interactive and instantaneous.

IronBarcode

Signalr C# (How It Works For Developers) Figure 4

Barcoding is integral in inventory management, ticketing systems, and more. Discover IronBarcode Capabilities simplifies the creation and reading of barcodes. Now, think of integrating this with SignalR in a warehouse management system. As items are scanned, the inventory gets updated in real-time, notifying connected clients of stock levels, and ensuring a smooth logistical operation.

Conclusion

Signalr C# (How It Works For Developers) Figure 5

The fusion of ASP.NET Core SignalR with Iron Suite's powerful tools promises an elevated experience for both developers and end-users. Real-time web functionality becomes not just about communication but a transformative tool that, when paired with the right resources like Iron Suite, can redefine interactive applications.

It's worth noting the value proposition offered by Iron Suite. Each product license starts from $799, providing developers with a premium set of features. However, if you're unsure about the immediate commitment, each product generously offers a free trial of Iron Software Products. This allows you to test-drive the capabilities before making a decision.

And, if you're considering integrating multiple tools, there's fantastic news: you can purchase the entire Iron Suite for added value for the price of just two products! This not only ensures you get the best bang for your buck but also equips you with a comprehensive toolkit to revolutionize your ASP.NET Core SignalR applications.

Häufig gestellte Fragen

Was ist SignalR und wie verbessert es Webanwendungen?

SignalR ist eine Bibliothek in ASP.NET Core, die Echtzeit-Webfunktionalität zu Anwendungen hinzufügt und sofortige Server-Client-Kommunikation ermöglicht. Dies führt zu interaktiven und reaktionsschnellen Webanwendungen, indem es Echtzeit-Updates und Rückmeldungen ermöglicht.

Wie kann ich SignalR in meiner C#-Anwendung einrichten?

Um SignalR in einer C#-Anwendung einzurichten, müssen Sie das ASP.NET Core SDK installieren und Visual Studio für die Entwicklung verwenden. Fügen Sie SignalR-Dienste in der Startup-Klasse hinzu und weisen Sie Hubs Endpunkten zu, um die Server-Client-Kommunikation herzustellen.

Welche Rolle spielt ein SignalR-Hub in der Echtzeitkommunikation?

Ein SignalR-Hub fungiert als zentrale Komponente, die die Kommunikation zwischen dem Server und den verbundenen Clients erleichtert. Er ermöglicht das Senden und Empfangen von Nachrichten in Echtzeit und ist ein Schlüsselelement der SignalR-Funktionalität.

Wie kann ich Echtzeit-Messaging in SignalR handhaben?

Echtzeit-Messaging in SignalR kann durch die Erstellung eines serverseitigen Hubs und eines clientseitigen Skripts verwaltet werden. Das clientseitige JavaScript baut eine Verbindung zum Hub auf und handhabt das Senden und Empfangen von Nachrichten mit Methoden wie connection.on und connection.send.

Was sind einige erweiterte Funktionen von SignalR?

SignalR bietet erweiterte Funktionen wie das Gruppieren von Verbindungen zur Segmentierung der Kommunikation, das elegante Handhaben von Client-Abbrüchen und die Unterstützung von Binärprotokollen für verbesserte Echtzeitkommunikationsfunktionen.

Wie hilft der Azure SignalR-Dienst bei der Skalierung von Anwendungen?

Azure SignalR Service ermöglicht es Anwendungen, zu skalieren, indem eine große Anzahl gleichzeitiger Verbindungen unterstützt wird. Dazu gehört die Installation des Azure SignalR SDK und die Konfiguration der Startup-Klasse, um die Infrastruktur von Azure für skalierbare Echtzeitkommunikation zu nutzen.

Wie kann IronPDF verwendet werden, um PDFs in einer SignalR-Anwendung zu erstellen?

IronPDF kann in einer SignalR-Anwendung verwendet werden, um PDF-Dokumente zu erstellen, indem HTML-Inhalte konvertiert werden. Die Methode RenderHtmlAsPdf von IronPDF ermöglicht eine nahtlose PDF-Erstellung, die in Echtzeit-Updates in SignalR integriert werden kann.

Welche Vorteile bringt IronXL für SignalR-Anwendungen?

IronXL verbessert SignalR-Anwendungen, indem es die Verwaltung von Excel-Dateien ermöglicht. Es erlaubt die Erstellung, das Lesen und die Modifizierung von Excel-Dokumenten innerhalb Ihrer Anwendung und bietet zusätzliche Datenverarbeitungsfähigkeiten neben den Echtzeit-Funktionalitäten.

Kann IronOCR in SignalR-Anwendungen für Texterkennung integriert werden?

Ja, IronOCR kann in SignalR-Anwendungen integriert werden, um optische Zeichenerkennung (OCR) durchzuführen. Dies ermöglicht die Echtzeit-Textextraktion aus Bildern und verbessert Anwendungen durch dynamische Texterkennungsfähigkeiten.

Welches Potenzial hat die Verwendung von IronBarcode in SignalR-Anwendungen?

IronBarcode kann in SignalR-Anwendungen verwendet werden, um Barcodes in Echtzeit zu erstellen und zu lesen. Diese Funktionalität ist vorteilhaft für Anwendungen, die dynamische Barcode-Verarbeitung und Echtzeit-Datenverarbeitung erfordern.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen