SignalR C#(開發者的工作原理)
現代網路以互動性和即時回饋為主。 在建立回應式應用程式時,即時網頁功能是必須的。這正是 SignalR 的優勢所在。 ASP.NET Core SignalR 是一個函式庫,可讓您在應用程式中加入即時網路功能,比您想像的還要簡單。
在本教程中,我們將開始一段有關 SignalR 的基礎知識和細微差異的旅程。 讓我們深入瞭解!
ASP.NET Core 中的 SignalR 簡介
ASP.NET Core SignalR 提供了一個 API,可使用 WebSockets 和其他技術(例如伺服器傳送的事件)建立即時網路功能。 不僅限於 ASP.NET Core。 您可以將 SignalR 與各種用戶端搭配使用,例如瀏覽器或行動應用程式,確保連線的用戶端即時更新。
設定您的開發環境
要開始工作,您需要
- ASP.NET Core SDK
- Visual Studio
建立 SignalR Hub
SignalR 的核心圍繞著 SignalR hub,也就是客戶端和伺服器互動的中心點。
建立一個新的 ASP.NET Core 專案。 現在,新增一個新類別,並將其命名為 ChatHub 。 這將成為我們的 SignalR 樞紐。
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在 Startup class 中,讓我們整合我們的集線器。
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用戶端實作
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>現在,您可以連接到集線器:
// 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}`);
});這個簡單的客戶端程式碼會連線到集線器,並監聽任何訊息廣播。
實作中的即時功能
傳送訊息
使用我們早期的客戶端和伺服器端程式碼片段,傳送訊息是很直接的。 伺服器和用戶端都可以啟動通訊。
從伺服器端:
// 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!")還有客戶的意見:
// 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()));進階即時通訊
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 ClassIron Suite 以優質 .NET 工具強化 SignalR
雖然 ASP.NET Core SignalR 為即時網頁功能提供了優異的基礎,但開發人員仍經常尋找工具來增強整體體驗和功能。 這就是 Iron Software Suite of Libraries 的切入點。
Iron Suite for .NET 是一套優質的 .NET 函式庫,專門為您的 ASP.NET Core 應用程式設計,包括使用 SignalR 的應用程式。 此套件中的每項產品都提供獨特的功能,以確保提供更豐富的應用程式體驗。 讓我們深入瞭解這些產品:
IronPDF。

Learn more about IronPDF capabilities 可讓您在 .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 ClassIronXL。

當談到使用 Excel 試算表時,探索 IronXL 功能是冠軍。 在商業環境中,試算表扮演著重要的角色。 將 SignalR 與 IronXL 結合,意味著財務團隊可以即時處理預算表,目睹發生的變化。 試想一下,各個部門的資料彙整成一個集中的 Excel 表單,並提供所有利害關係人即時更新。 即時溝通與動態試算表管理的融合在此組合下成為現實。
IronOCR。

光學字元識別 (OCR) 已經成為現代應用程式的主要功能。 See IronOCR in action 賦予 .NET 開發人員從影像和文件中萃取文字的能力。 搭配 SignalR 的即時功能可以改變遊戲規則。 考慮使用者上傳包含文字資料圖片的平台。 一旦 IronOCR 處理影像,SignalR 就可以用來即時通知使用者,讓資料擷取變得互動且即時。
IronBarcode。

BarCode 在庫存管理、票務系統等方面不可或缺。 發現 IronBarcode 功能簡化了條碼的建立和讀取。 現在,請考慮將此與倉庫管理系統中的 SignalR 整合。 當商品被掃描時,庫存會即時更新,通知相關客戶庫存水平,並確保順利的物流作業。
結論

ASP.NET Core SignalR 與 Iron Suite 強大工具的融合,可為開發人員和終端使用者帶來更高的使用體驗。 即時網路功能變得不僅僅是溝通,而是一種變革工具,搭配 Iron Suite 等正確的資源,可以重新定義互動應用程式。
值得注意的是 Iron Suite 所提供的價值主張。每個產品授權的起價為 $799 ,提供開發人員一系列的優質功能。 但是,如果您不放心立即投入使用,每種產品都會慷慨地提供 免費試用 Iron Software 產品。 這可讓您在做決定之前先試用其功能。
此外,如果您正在考慮整合多種工具,還有一個好消息:您可以 購買整個 Iron Suite 以獲得附加價值,而價格只需購買兩項產品! 這不僅能確保您獲得最佳的經濟效益,還能讓您擁有全面的工具包,為您的 ASP.NET Core SignalR 應用程式帶來革命性的改變。
常見問題解答
什麼是 SignalR,它如何增強網路應用程式?
SignalR 是 ASP.NET Core 中的一個函式庫,可為應用程式增加即時網頁功能,實現伺服器與用戶端的即時通訊。透過實時更新和回饋,可產生互動且反應迅速的 Web 應用程式。
如何在 C# 應用程式中設定 SignalR?
要在 C# 應用程式中設定 SignalR,您需要安裝 ASP.NET Core SDK 並使用 Visual Studio 進行開發。在 Startup 類別中加入 SignalR 服務,並將 hub 對應到端點,以建立伺服器與用戶端的通訊。
SignalR Hub 在即時通訊中扮演什麼角色?
SignalR Hub 是一個中央元件,可促進伺服器與連接的用戶端之間的通訊。它可以實時傳送和接收訊息,是 SignalR 功能的關鍵部分。
如何在 SignalR 中處理即時訊息傳送?
SignalR 中的即時訊息傳輸可透過建立伺服器端樞紐和用戶端腳本來管理。用戶端的 JavaScript 會建立與 hub 的連線,並使用 connection.on 和 connection.send 等方法處理訊息的傳送和接收。
SignalR 有哪些進階功能?
SignalR 提供先進的功能,例如將連線群組以分割通訊、優雅處理用戶端斷線,以及支援二進位通訊協定以增強即時通訊能力。
Azure SignalR 服務如何協助擴充應用程式?
Azure SignalR 服務可支援大量同時連線,讓應用程式得以擴充。它涉及安裝 Azure SignalR SDK 並配置 Startup 類別,以利用 Azure 的基礎架構進行可擴充的即時通訊。
如何使用 IronPDF 在 SignalR 應用程式中產生 PDF?
IronPDF 可以用在 SignalR 應用程式中,透過轉換 HTML 內容來產生 PDF 文件。IronPDF 的 RenderHtmlAsPdf 方法允許無縫生成 PDF,可以與 SignalR 中的實時更新整合。
IronXL 能為 SignalR 應用程式帶來哪些好處?
IronXL 透過啟用 Excel 檔案操作增強 SignalR 應用程式。它允許您在應用程式中建立、讀取和修改 Excel 文件,在實時功能之外提供額外的資料處理能力。
IronOCR 可以整合到 SignalR 應用程式中進行文字辨識嗎?
是的,IronOCR 可以整合到 SignalR 應用程式中執行光學字元識別 (OCR)。這可從影像中即時擷取文字,增強應用程式的動態文字辨識能力。
在 SignalR 應用程式中使用 IronBarcode 的潛力為何?
IronBarcode 可在 SignalR 應用程式中使用,以即時產生和讀取條碼。此功能有利於需要動態條碼處理和即時資料處理的應用程式。







