.NET 幫助

HttpListener C#(它如何為開發人員工作)

發佈 2024年8月13日
分享:

介紹

在 C# 中構建基本獨立網絡伺服器最有用的工具之一是 HttpListener 類。它包含在 System.Net 命名空間中,並提供了一種接收和回應的方法。 超文本傳輸協定 來自客戶的請求。這對於在桌面程式中管理基於網絡的通信或構建輕量級的在線服務特別有幫助。

一個叫做的 .NET 庫 IronPDF 用於生成、修改和提取PDF文件內容。它提供了從HTML創建PDF、將已有的PDF轉換成不同格式以及使用程式碼來修改PDF的全面功能。

開發人員可以結合HttpListener和IronPDF設計出能夠根據HTTP請求動態生成並提供PDF文件的網絡服務。對於需要根據使用者輸入或其他動態數據生成實時PDF的應用程式來說,這將非常有用。

什麼是 HttpListener C#?

HttpListener 是一個簡單但靈活的類別,在.NET Framework的System.Net命名空間中,使開發人員能夠用C#設計簡單的HTTP伺服器。其目的是接收來自客戶的HTTP請求,處理它們,並回應適當的信息。由於不需要像IIS這樣的全功能web伺服器,這個類別對於輕量級、獨立的web服務或者將基於web的通信功能整合到桌面程序中是一個很好的選擇。

HttpListener C#(對開發人員的運作方式):圖1

開發人員可以使用 HttpListener 設定 URI 前綴,以確定伺服器應該聆聽哪些地址。啟動監聽器後,它會響應所有收到的請求,並使用 HttpListenerContext 提供對請求和回應對象的訪問權限。此配置使根據應用程式需求創建特定的 HTTP 請求處理邏輯成為可能。HttpListener 的易用性和適應性使其在需要快速、高效且可配置的 HTTP 伺服器的情況下特別有用。HttpListener 提供了一個穩定的解決方案,沒有多餘的負擔,非常適合開發本地伺服器以進行測試、原型化線上服務或將通信協議整合到桌面應用中。

HttpListener C# 的功能

C# 的 HttpListener 是构建 HTTP 服务器的有效工具,具有多项功能。以下是其中一些重要元素:

易于使用: HttpListener 是一个易于使用的库,程序员可以通过编写更少的代码来建立基本的 HTTP 服务器。

URI 前缀: 可以指定多个 URI 前缀进行监听,这提供了灵活性,以处理各种端点并确保服务器只对相关查询做出反应。

异步操作: HttpListener 支持异步方法,这通过高效地同时处理大量请求而不中断主线程,增强了服务器的可扩展性和响应能力。

认证: 使用 HttpListener 可以根据需要对端点进行安全保护,支持多种认证技术,如 Basic、Digest、NTLM 和集成 Windows 身份验证。

HTTPS 支持: HttpListener 可以设置为响应 HTTPS 请求,例如,启用安全的客户端-服务器数据通信。

请求和响应处理: HttpListener 允许您完全控制请求和响应过程,通过添加新的头文件、状态码和内容类型来更改响应,并读取请求数据、头文件和参数。

监听器配置: HttpListener 提供特定于监听器的配置选项来调整服务器行为,如证书管理。 (適用於 HTTPS), 超時和其他參數。

日誌記錄和診斷: 啟用日誌記錄和診斷,提供全面的請求和響應資訊,便於監控和故障排除。

兼容性: 由於它與其他 .NET 組件和庫運行良好,允許與目前的 .NET 服務和應用程式平滑集成。

跨平台: HttpListener 兼容 Windows、Linux 和 macOS,且配合 .NET Core 和 .NET 5+ 使用,提供了跨平台開發的靈活性。

Create and Config HttpListener C

創建和配置 HttpListener 在 C# 中涉及多個步驟。關於配置 HttpListener 來處理 HTTP 請求的詳細教程可以在下面找到。

創建一個新的 .NET 項目

打開您的命令提示符、控制台或終端。

通過鍵入啟動新創建的 .NET 控制台應用程序

dotnet new console -n HttplistenerExample
cd HttplistenerExample
dotnet new console -n HttplistenerExample
cd HttplistenerExample
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

建立一個 HttpListener 實例

首先,建立一個 HttpListener 類別的實例。

配置 URI 前綴

添加 URI 前綴以指定監聽器應處理的地址。

啟動監聽器

啟動 HttpListener 以開始監聽傳入的 HTTP 請求。

處理傳入的請求

創建一個循環來處理傳入的請求,處理它們並發送回應。

停止監聽器

當不再需要時,優雅地停止 HttpListener。

以下是一個只展示這些階段之一的請求範例:

using System;
using System.Net;
using System.Text;
class Program
{
    public static string url="http://localhost:8080/";
    public static HttpListener listener;
    public static void Main(string[] args)
    {
        // Step 1: Create an HttpListener instance
        listener = new HttpListener();
        // Step 2: Configure URI prefixes
        listener.Prefixes.Add(url);
        // Step 3: Start the listener
        listener.Start();
        Console.WriteLine("Listening for requests on "+url);
        // Step 4: Handle incoming requests
    // Wait for an incoming request
        while (true)
        {
            // getcontext method blocks
            HttpListenerContext context = listener.GetContext();
            HttpListenerRequest request = context.Request;
            // Process the request (e.g., log the request URL with or without query string)
            Console.WriteLine($"Received request for {request.Url}");
            // Create a response
            HttpListenerResponse response = context.Response;
        // add response info
            string responseString = "<html><body>Hello, world!</body></html>";
            byte[] buffer = Encoding.UTF8.GetBytes(responseString);
            // Set the content length and type
            response.ContentLength64 = buffer.Length;
            response.ContentType = "text/html";
            // Write the response to the output stream
            using (System.IO.Stream output = response.OutputStream)
            {
                output.Write(buffer, 0, buffer.Length);
            }
            // Close the response
            response.Close();
        }
        // Step 5: Stop the listener (this code is unreachable in the current loop structure)
        // listener.Stop();
    }
}
using System;
using System.Net;
using System.Text;
class Program
{
    public static string url="http://localhost:8080/";
    public static HttpListener listener;
    public static void Main(string[] args)
    {
        // Step 1: Create an HttpListener instance
        listener = new HttpListener();
        // Step 2: Configure URI prefixes
        listener.Prefixes.Add(url);
        // Step 3: Start the listener
        listener.Start();
        Console.WriteLine("Listening for requests on "+url);
        // Step 4: Handle incoming requests
    // Wait for an incoming request
        while (true)
        {
            // getcontext method blocks
            HttpListenerContext context = listener.GetContext();
            HttpListenerRequest request = context.Request;
            // Process the request (e.g., log the request URL with or without query string)
            Console.WriteLine($"Received request for {request.Url}");
            // Create a response
            HttpListenerResponse response = context.Response;
        // add response info
            string responseString = "<html><body>Hello, world!</body></html>";
            byte[] buffer = Encoding.UTF8.GetBytes(responseString);
            // Set the content length and type
            response.ContentLength64 = buffer.Length;
            response.ContentType = "text/html";
            // Write the response to the output stream
            using (System.IO.Stream output = response.OutputStream)
            {
                output.Write(buffer, 0, buffer.Length);
            }
            // Close the response
            response.Close();
        }
        // Step 5: Stop the listener (this code is unreachable in the current loop structure)
        // listener.Stop();
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

下面的 C# 代碼演示了創建和配置 HttpListener 的過程,該 HttpListener 作為基本的 HTTP 伺服器運行。為了定義它將處理請求的地址,首先實例化一個 HttpListener 對象並附加一個 URI 前綴。 (http://localhost:8080/)接著,使用 Start 方法來啟動監聽器。我們利用無限的 while 迴圈來持續監聽新的 HTTP 請求。在迴圈中,GetContext 等待請求,然後返回一個包含請求和回應物件的 HttpListenerContext 物件。

HttpListener C#(開發人員如何運作):圖 2

在記錄請求URL之後,會創建一個簡單的HTML和響應對象,轉換為字節數組,並發送到響應輸出流。在向客戶端返回響應之前,會正確指定響應的類型和持續時間。循環意味著伺服器永遠不會停止處理請求,一次接一次。需要調用halt方法來停止請求控制台的監聽器,但在此情況下,無限循環使其無法到達。

HttpListener C#(它對開發者的工作原理):圖 3

入門

IronPDF 可以幫助你在 .NET 中製作和修改高品質的 PDF,這對於創建文件和報告是必需的。HttpListener 的內建 HTTP 伺服器功能允許你在小型應用程式或服務中管理網頁請求。這兩個工具在各自的領域內都提高了 .NET 應用程式的實用性和速度。要開始使用 C# 的 HttpListener 並將其與 IronPDF 集成以創建 PDF,請採取以下行動:

什麼是 IronPDF?

功能豐富的 .NET 庫 IronPDF 允許C# 程式生成、閱讀和編輯 PDF 文件。借助此工具,開發人員可以快速將 HTML、CSS 和 JavaScript 資料轉換為高品質且可列印的 PDF。最重要的任務包括添加頁眉和頁腳、分割和合併 PDF、給文件添加水印以及將 HTML 轉換為 PDF。IronPDF 支援 .NET Framework 和 .NET Core,對於各種應用程式都十分有用。

由於 PDF 易於使用且包含大量信息,開發人員可以輕鬆地將它們包含在產品中。因為 IronPDF 可以處理複雜的數據佈局和格式化,它生成的 PDF 輸出與客戶或原始 HTML 文本非常相似。

HttpListener C#(它如何為開發者工作):圖4

IronPDF 的功能

從 HTML 生成 PDF

將 JavaScript、HTML 和 CSS 轉換為 PDF。IronPDF 支持媒體查詢和響應式設計,這是兩種當代的網頁標準。它對現代網頁標準的支持有助於動態裝飾 PDF 報告、發票和使用 HTML 和 CSS 的文件。

PDF 編輯

可以在現有的 PDF 中添加文本、圖像和其他內容。通過 IronPDF,開發者可以從 PDF 文件中提取文本和圖像,將多個 PDF 合併為一個文件,將 PDF 文件拆分為多個單獨的文件,並在 PDF 頁面中包含水印、註釋、頁首和頁腳。

PDF 轉換

將多種文件格式(包括 Word、Excel 和圖像文件)轉換為 PDF。IronPDF 也支持 PDF 到圖像的轉換。 (PNG,JPEG 等。).

性能和可靠性

高性能和可靠性是工業環境中理想的設計品質。開發人員可以輕鬆管理大型文檔集。

安裝 IronPDF

若要獲得在 .NET 專案中處理 PDF 所需的工具,請安裝 IronPDF 套件。

dotnet add package IronPdf
dotnet add package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'dotnet add package IronPdf
VB   C#

結合 HttpListener C# 與 IronPDF

這是一個全面的示例,向您展示如何使用 IronPDF 建立和提供 PDF 文件並設置 HttpListener:

using System;
using System.Net;
using System.Text;
using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        // Step 1: Create an HttpListener instance
        HttpListener listener = new HttpListener();
        // Step 2: Configure URI prefixes
        listener.Prefixes.Add("http://localhost:8080/");
        // Step 3: Start the listener
        listener.Start();
        Console.WriteLine("Listening for requests on http://localhost:8080/");
        // Step 4: Handle incoming requests
        while (true)
        {
            // Wait for an incoming request
            HttpListenerContext context = listener.GetContext();
            HttpListenerRequest request = context.Request;
            // Process the request (e.g., log the request URL)
            Console.WriteLine($"Received request for {request.Url}");
            // Generate PDF using IronPDF
            var htmlContent = "<h1>PDF generated by IronPDF</h1><p>This is a sample PDF document.</p>";
            var pdf = IronPdf.HtmlToPdf.StaticRenderHtmlAsPdf(htmlContent);
            // Get the PDF as a byte array
            byte[] pdfBytes = pdf.BinaryData;
            // Create a response
            HttpListenerResponse response = context.Response;
            // Set the content length and type
            response.ContentLength64 = pdfBytes.Length;
            response.ContentType = "application/pdf";
            // Write the PDF to the response output stream
            using (System.IO.Stream output = response.OutputStream)
            {
                output.Write(pdfBytes, 0, pdfBytes.Length);
            }
            // Close the response
            response.Close();
        }
        // Step 5: Stop the listener (this code is unreachable in the current loop structure)
        // listener.Stop();
    }
}
using System;
using System.Net;
using System.Text;
using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        // Step 1: Create an HttpListener instance
        HttpListener listener = new HttpListener();
        // Step 2: Configure URI prefixes
        listener.Prefixes.Add("http://localhost:8080/");
        // Step 3: Start the listener
        listener.Start();
        Console.WriteLine("Listening for requests on http://localhost:8080/");
        // Step 4: Handle incoming requests
        while (true)
        {
            // Wait for an incoming request
            HttpListenerContext context = listener.GetContext();
            HttpListenerRequest request = context.Request;
            // Process the request (e.g., log the request URL)
            Console.WriteLine($"Received request for {request.Url}");
            // Generate PDF using IronPDF
            var htmlContent = "<h1>PDF generated by IronPDF</h1><p>This is a sample PDF document.</p>";
            var pdf = IronPdf.HtmlToPdf.StaticRenderHtmlAsPdf(htmlContent);
            // Get the PDF as a byte array
            byte[] pdfBytes = pdf.BinaryData;
            // Create a response
            HttpListenerResponse response = context.Response;
            // Set the content length and type
            response.ContentLength64 = pdfBytes.Length;
            response.ContentType = "application/pdf";
            // Write the PDF to the response output stream
            using (System.IO.Stream output = response.OutputStream)
            {
                output.Write(pdfBytes, 0, pdfBytes.Length);
            }
            // Close the response
            response.Close();
        }
        // Step 5: Stop the listener (this code is unreachable in the current loop structure)
        // listener.Stop();
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

包含的C#代碼展示了如何連接 IronPDF 使用 HttpListener 動態生成和傳送 PDF 文件,以及如何設置將其功能與基本的 HTTP 方法伺服器。第一步是創建一個 HttpListener 實例,並將其設置為在 http://localhost:8080/ 監聽 HTTP 請求。

啟動監聽器後,將進入無限循環以處理傳入的請求。代碼將記錄每次請求的請求 URL,使用 IronPDF 從 HTML 文本創建 PDF 文件,然後將 PDF 轉換為字節數組。接下來,將使用適當的 MIME 類型設置響應。 (應用程式/pdf) 和內容長度。

HttpListener C#(開發人員使用方式):圖 5

第一個響應流在將 PDF 字節數組寫入響應輸出流後關閉,以將其發送回客戶端。通過此配置,服務器可以有效地響應 HTTP 請求並動態返回創建的 PDF 文件。

HttpListener C# (開發者的工作方式):圖 6

結論

總結來說,使用 IronPDF 結合 C#的 HttpListener 提供了一種可靠的方法來動態地創建並通過 HTTP 傳遞 PDF 文件。借助 HttpListener,C#應用程序可以創建輕量級的 HTTP 伺服器,能夠處理傳入的請求並提供靈活的響應生成。通過利用 IronPDF 的動態 HTML 到 PDF 轉換功能,開發人員可以有效地生成自定義或數據驅動的 PDF 報表、發票或其他文件,直接來自伺服器端邏輯。

需要通過網頁界面或 API 實時生成和傳遞文檔的應用程序可能會發現這種組合特別有用。開發人員可以通過實施可擴展和響應迅速的解決方案來應對特定的業務需求,使用 HttpListener 和 IronPDF 來提高用戶體驗,促進無縫的文檔生成和在線傳遞。

您可以通過使用 IronPDF 來改進您的 .NET 開發工具箱,包括 OCR、處理條形碼、創建 PDF、連接到 Excel 等等。 IronSoftware 提供開發者更強大的網頁應用程式和功能,並以更有效的開發起步價 $749。這是通過將其基本基礎與高度靈活的Iron Software套件和技術結合起來實現的。

通過清楚概述針對專案量身定制的許可選項,簡化開發者選擇最佳模型的流程。這些優勢使開發者能夠以有效、及時和協調的方式應用各種問題的解決方案。

< 上一頁
Autofac C#(它如何為開發人員工作)
下一個 >
AutoFixture C#(開發人員的工作方式)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >