HttpListener提供一個簡單的、可通過編程方式控制的 HTTP 協議接聽程式.使用它可以很容易的提供一些Http服務,而無需啟動IIS這類大型服務程式。使用HttpListener的方法流程很簡單:主要分為以下幾步
1.建立一個HTTP接聽程式對象並初始化
2.添加需要監聽的URI 首碼
3.開始偵聽來自用戶端的請求
4.處理用戶端的Http請求
5.關閉HTTP接聽程式
例如:我們要實現一個簡單Http服務,進行檔案的下載,或者進行一些其他的操作,例如要發送郵件,使用HttpListener監聽,處理郵件隊列,避免在網站上的同步等待。以及擷取一些緩衝的資料等等行為
using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Text;using System.Threading;using System.Web;using System.IO;using Newtonsoft.Json;namespace HttpListenerApp{ /// <summary> /// HttpRequest邏輯處理 /// </summary> public class HttpProvider { private static HttpListener httpFiledownload; //檔案下載處理請求監聽 private static HttpListener httOtherRequest; //其他超做請求監聽 /// <summary> /// 開啟HttpListener監聽 /// </summary> public static void Init() { httpFiledownload = new HttpListener(); //建立監聽執行個體 httpFiledownload.Prefixes.Add("http://10.0.0.217:20009/FileManageApi/Download/"); //添加監聽地址 注意是以/結尾。 httpFiledownload.Start(); //允許該監聽地址接受請求的傳入。 Thread ThreadhttpFiledownload = new Thread(new ThreadStart(GethttpFiledownload)); //建立開啟一個線程監聽該地址得請求 ThreadhttpFiledownload.Start(); httOtherRequest = new HttpListener(); httOtherRequest.Prefixes.Add("http://10.0.0.217:20009/BehaviorApi/EmailSend/"); //添加監聽地址 注意是以/結尾。 httOtherRequest.Start(); //允許該監聽地址接受請求的傳入。 Thread ThreadhttOtherRequest = new Thread(new ThreadStart(GethttOtherRequest)); ThreadhttOtherRequest.Start(); } /// <summary> /// 執行檔案下載處理請求監聽行為 /// </summary> public static void GethttpFiledownload() { while (true) { HttpListenerContext requestContext = httpFiledownload.GetContext(); //接受到新的請求 try { //reecontext 為開啟線程傳入的 requestContext請求對象 Thread subthread = new Thread(new ParameterizedThreadStart((reecontext) => { Console.WriteLine("執行檔案處理請求監聽行為"); var request = (HttpListenerContext)reecontext; var image = HttpUtility.UrlDecode(request.Request.QueryString["imgname"]); //接受GET請求過來的參數; string filepath = AppDomain.CurrentDomain.BaseDirectory + image; if (!File.Exists(filepath)) { filepath = AppDomain.CurrentDomain.BaseDirectory + "default.jpg"; //下載預設圖片 } using (FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read)) { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, (int)fs.Length); //將檔案讀到緩衝區 request.Response.StatusCode = 200; request.Response.Headers.Add("Access-Control-Allow-Origin", "*"); request.Response.ContentType = "image/jpg"; request.Response.ContentLength64 = buffer.Length; var output = request.Response.OutputStream; //擷取請求流 output.Write(buffer, 0, buffer.Length); //將緩衝區的位元組數寫入當前請求流返回 output.Close(); } })); subthread.Start(requestContext); //開啟處理線程處理下載檔案 } catch (Exception ex) { try { requestContext.Response.StatusCode = 500; requestContext.Response.ContentType = "application/text"; requestContext.Response.ContentEncoding = Encoding.UTF8; byte[] buffer = System.Text.Encoding.UTF8.GetBytes("System Error"); //對用戶端輸出相應資訊. requestContext.Response.ContentLength64 = buffer.Length; System.IO.Stream output = requestContext.Response.OutputStream; output.Write(buffer, 0, buffer.Length); //關閉輸出資料流,釋放相應資源 output.Close(); } catch { } } } } /// <summary> /// 執行其他超做請求監聽行為 /// </summary> public static void GethttOtherRequest() { while (true) { HttpListenerContext requestContext = httOtherRequest.GetContext(); //接受到新的請求 try { //reecontext 為開啟線程傳入的 requestContext請求對象 Thread subthread = new Thread(new ParameterizedThreadStart((reecontext) => { Console.WriteLine("執行其他超做請求監聽行為"); var request = (HttpListenerContext)reecontext; var msg = HttpUtility.UrlDecode(request.Request.QueryString["behavior"]); //接受GET請求過來的參數; //在此處執行你需要進行的操作>>比如什麼快取資料讀取,隊列訊息處理,郵件訊息佇列添加等等。 request.Response.StatusCode = 200; request.Response.Headers.Add("Access-Control-Allow-Origin", "*"); request.Response.ContentType = "application/json"; requestContext.Response.ContentEncoding = Encoding.UTF8; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new { success = true, behavior = msg })); request.Response.ContentLength64 = buffer.Length; var output = request.Response.OutputStream; output.Write(buffer, 0, buffer.Length); output.Close(); })); subthread.Start(requestContext); //開啟處理線程處理下載檔案 } catch (Exception ex) { try { requestContext.Response.StatusCode = 500; requestContext.Response.ContentType = "application/text"; requestContext.Response.ContentEncoding = Encoding.UTF8; byte[] buffer = System.Text.Encoding.UTF8.GetBytes("System Error"); //對用戶端輸出相應資訊. requestContext.Response.ContentLength64 = buffer.Length; System.IO.Stream output = requestContext.Response.OutputStream; output.Write(buffer, 0, buffer.Length); //關閉輸出資料流,釋放相應資源 output.Close(); } catch { } } } } }}
調用方式:注意這裡啟動程式必須以管理員身份運行,因為上午的監聽需要開啟連接埠,所有需要以管理員身份運行。
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace HttpListenerApp{ class Program { static void Main(string[] args) { //開啟請求監聽 HttpProvider.Init(); } }}
執行後的結果為:
這裡通過一個簡單的控製程序在裡面使用HttpListener實現了簡單的Http服務程式。裡面有少量的線程和和非同步處理,比如收到行為資訊請求可以先返回給使用者,讓使用者不用同步等待,就可以執行下一步操作,又比如實現的簡單郵件伺服器,將請求發給HttpListener接收到請求後就立即返回,交給隊列去發送郵件。郵件的發送會出現延遲等待等情況出現,這樣就不用等待。
以上就是.NET下通過HttpListener實現簡單的Http服務 的內容,更多相關內容請關注topic.alibabacloud.com(www.php.cn)!