跳過到頁腳內容
.NET幫助

SignalR C#(開發者的工作原理)

現代網路因互動性和即時反饋而蓬勃發展。 在構建響應式應用程式時,即時網路功能是必需的。這就是 SignalR 大放異彩的地方。 ASP.NET Core SignalR 是一個使將即時網路功能添加到您的應用程式比您想像的更簡單的庫。

在本教程中,我們將涉足 SignalR 的基本和細微特性。 讓我們深入探討一下吧!

ASP.NET Core 中的 SignalR 介紹

ASP.NET Core SignalR 提供了一個 API 用於使用 WebSockets 和其他技術(如伺服器推送事件)創建即時網路功能。 這不僅限於 ASP.NET Core。 您可以在多種客戶端(如瀏覽器或移動應用程式)中使用 SignalR,確保連接的客戶端即時更新。

設置您的開發環境

要開始,您需要:

構建 SignalR Hub

SignalR 的核心圍繞 SignalR hub,這是一個客戶端和伺服器交互的中央點。

創建一個新的 ASP.NET Core 專案。 現在,添加一個新的類別並命名為 ChatHub。 這將作為我們的 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

Startup 類中,讓我們整合我們的 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

客戶端實現

SignalR 多用途。雖然本教程著重於ASP.NET Core 和 JavaScript 客戶端庫,SignalR 支援多種客戶端,從 .NET 到 Java。

使用 SignalR 客戶端庫

SignalR 客戶端庫允許您的客戶端代碼直接與伺服器端連接和通信。以我們的例子,讓我們使用 JavaScript。

首先,添加 SignalR JavaScript 客戶端庫:

<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

現在,您可以連接到 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

這段簡單的客戶端代碼連接到 hub 並監聽所有廣播的訊息。

實時功能運作中

傳送訊息

使用我們之前的客戶端和伺服器端代碼片段,傳送訊息很簡單。 伺服器和客戶端都可以發起通信。

從伺服器端:

// 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

從客戶端:

// 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

高級實時通信

ASP.NET Core SignalR 提供高級實時通信功能:

  1. 分組連接:將連接的客戶端分段,向特定分段廣播消息。
  2. 處理斷開連接:自動管理客戶端連接和斷開連接。
  3. 二進制協議:雖然 SignalR 默認使用基於文本的協議,但它也支援二進制協議。

使用 Azure SignalR 服務的 SignalR

要實現可擴展的實時功能,整合 Azure SignalR Service。 這個完全托管的服務支援大量同步連接,非常適合高需求的應用程式。

整合 Azure SignalR 服務:

  1. 安裝 Azure SignalR SDK
  2. 使用 Azure Service Bus 支援後端總線。
  3. 調整 Startup 類以使用 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 使用高級 .NET 工具提升 SignalR

雖然 ASP.NET Core SignalR 為實時網路功能提供了一個出色的基礎,但開發者通常尋找工具來增強整體體驗和功能。 這就是 Iron Software Suite of Libraries 出現的地方。

Iron Suite 是一套高級 .NET 庫,旨在增強您的 ASP.NET Core 應用程式,包括那些使用 SignalR 的應用程式。 此套件中的每個產品都提供獨特的功能,確保更豐富的應用程式體驗。 讓我們深入了解這些產品的功能:

IronPDF

Signalr C#(開發人員如何使用)圖 1

了解更多有關 IronPDF 功能 允許您在 .NET 應用程式中生成、編輯和閱讀 PDF 文件。 想像一下在一個團隊合作撰寫文檔的場景中集成 SignalR。當更改發生時,該文檔可以即時轉換為 PDF,並將更新無縫推送到所有連接的客戶端。 SignalR 的即時功能與 IronPDF 的功能相結合可能會徹底改變協作工具。

IronPDF 將 HTML、URL 和完整網頁轉換為與原始相似的精美 PDF。 這是保存在線報告、發票或任何您想保留的網路信息的完美選擇。您是否在尋找將 HTML 轉換為 PDF? 立即嘗試 IronPDF!

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#(開發人員如何使用)圖 2

當涉及到 Excel 試算表的處理時,探索 IronXL 功能 是一個冠軍。 在商業環境中,試算表起著至關重要的作用。 集成 SignalR 和 IronXL 意味著財務團隊可以在實時進行預算表的工作,並即時看到變化。 設想一個場景,來自各部門的數據輸入流入集中 Excel 表格,讓所有利益相關者即時更新。 這一結合的實時通信和動態表格管理使這一切變為可能。

IronOCR

Signalr C#(開發人員如何使用)圖 3

光學字符識別(OCR)已成為現代應用程式中的基本要素。 觀察 IronOCR 如何運作 賦予 .NET 開發人員從圖像和文件中提取文本的能力。 將其與 SignalR 的實時功能結合起來可能會帶來變革。 考慮一個平台,允許用戶上傳包含文本數據的圖像。 SignalR 可用來實時通知用戶一旦 IronOCR 處理完成圖像,使數據提取互動且瞬時。

IronBarcode

Signalr C#(開發人員如何使用)圖 4

條形碼在庫存管理、票務系統等中具有重要作用。 探索 IronBarcode 功能 簡化了條形碼的創建和閱讀。 現在,想像一下在倉庫管理系統中與 SignalR 整合。 當物品被掃描時,庫存即時更新,通知連接的客戶端有關庫存水平,確保物流運營順利進行。

結論

Signalr C#(開發人員如何使用)圖 5

ASP.NET Core SignalR 與 Iron Suite 強大的工具相融合,為開發人員和終端用戶提供了一種升級的體驗。 實時網路功能不僅僅關於通信,而是一種變革性工具,當與像 Iron Suite 這樣的資源結合時,可以重新定義互動應用程式。

值得注意的是 Iron Suite 所提供的價值主張。每個產品的許可證起始於 $799,為開發人員提供了一組高級功能。 然而,如果您對立即投入感到不確定,每個產品慷慨地提供了一個 Iron Software 產品的免費試用版。 這使您可以在做出決定之前試用這些功能。

如果您考慮整合多個工具,這裡還有一個好消息:您可以 購買整個 Iron Suite 獲得更高價值 只需支付兩個產品的價格! 這不僅確保您獲得最佳的性價比,還提供了一個全面的工具包,以革命化您的 ASP.NET Core SignalR 應用程式。

常見問題解答

什麼是 SignalR,它如何增強網路應用程式?

SignalR 是 ASP.NET Core 中的一個庫,為應用程式添加即時網頁功能,實現即時的服務器-客戶端通信。通過允許即時更新和反饋,這導致了互動和響應式的網頁應用程式。

我如何在我的 C# 應用程式中設置 SignalR?

要在 C# 應用程式中設置 SignalR,您需要安裝 ASP.NET Core SDK 並使用 Visual Studio 進行開發。在 Startup 類中添加 SignalR 服務並將 hub 映射到端點以建立服務器-客戶端通信。

SignalR Hub 在即時通信中的作用是什麼?

SignalR Hub 是作為中央組件,促進服務器和已連接客戶端之間的通信。它使得即時發送和接收消息成為可能,是 SignalR 功能的一個關鍵部分。

我如何在 SignalR 中處理即時消息?

SignalR 中的即時消息可以通過創建服務器端 hub 和客戶端腳本來管理。客戶端 JavaScript 建立與 hub 的連接,並使用 connection.onconnection.send 這樣的方法處理發送和接收消息。

SignalR 的一些高級功能是什麼?

SignalR 提供了高級功能,例如分組連接以分段通信、優雅地處理客戶端斷線,並支持加強即時通信能力的二進制協議。

Azure SignalR 服務如何幫助擴展應用程式?

Azure SignalR 服務允許應用程式擴展支持大量同時連接。這需要安裝 Azure SignalR SDK 並配置 Startup 類以利用 Azure 基礎設施實現可擴展的即時通信。

如何在 SignalR 應用程式中使用 IronPDF 生成 PDF?

IronPDF 可以在 SignalR 應用程式中用於生成 PDF 文件,通過轉換 HTML 內容。IronPDF 的 RenderHtmlAsPdf 方法允許無縫 PDF 生成,這可以與 SignalR 的即時更新集成。

IronXL 為 SignalR 應用程式帶來什麼好處?

IronXL 增強 SignalR 應用程式,通過啟用 Excel 文件操作。它允許您在應用程式中創建、讀取和修改 Excel 文件,提供除即時功能以外的其他數據處理能力。

IronOCR 能否集成到 SignalR 應用程式中進行文本識別?

是的,IronOCR 可以集成到 SignalR 應用程式中以執行光學字符識別 (OCR)。這允許從圖像中提取即時文字,增強應用程式的動態文本識別功能。

IronBarcode 在 SignalR 應用程式中的潛力是什麼?

IronBarcode 可以在 SignalR 應用程式中用於生成和讀取條碼實時。這個功能對需要動態條碼處理和即時數據處理的應用程式有利。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。