跳過到頁腳內容
.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);
    }
}
$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");
        });
    }
}
$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!");
$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 Service配合使用

為了獲得可擴展的即時功能,整合Azure SignalR Service。 這個完全托管的服務支援大規模同時連接,非常適合高需求的應用程式。

整合Azure SignalR Service:

  1. 安裝Azure SignalR SDK
  2. 使用Azure服務匯流排做為後端支援。
  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");
        });
    }
}
$vbLabelText   $csharpLabel

Iron Suite以高級.NET工具增強SignalR

雖然ASP.NET Core SignalR提供了出色的即時網路功能基礎,開發人員通常尋找工具來增強整體體驗和功能。 那就是Iron Software套件程式庫的用武之地。

Iron Suite是一系列高級.NET程式庫,專為提升您的ASP.NET Core應用程式而設計,包括使用SignalR的應用。 該套件中的每個產品都提供了獨特的功能,確保更豐富的應用體驗。 讓我們深入了解其產品:

IronPDF

Signalr C# (開發者運作方式) 圖1

了解更多IronPDF功能讓您可以在.NET應用程式中生成、編輯和閱讀PDF文件。 設想一個情景,團隊在實時協作處理文檔。隨著變更的發生,文件可以即時轉換為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");
    }
}
$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 應用程式中用於生成和讀取條碼實時。這個功能對需要動態條碼處理和即時數據處理的應用程式有利。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me