.NET下通過(guò)HttpListener實(shí)現(xiàn)簡(jiǎn)單的Http服務(wù)
HttpListener提供一個(gè)簡(jiǎn)單的、可通過(guò)編程方式控制的 HTTP 協(xié)議偵聽(tīng)器.使用它可以很容易的提供一些Http服務(wù),而無(wú)需啟動(dòng)IIS這類大型服務(wù)程序。使用HttpListener的方法流程很簡(jiǎn)單:主要分為以下幾步
1.創(chuàng)建一個(gè)HTTP偵聽(tīng)器對(duì)象并初始化
2.添加需要監(jiān)聽(tīng)的URI 前綴
3.開(kāi)始偵聽(tīng)來(lái)自客戶端的請(qǐng)求
4.處理客戶端的Http請(qǐng)求
5.關(guān)閉HTTP偵聽(tīng)器
例如:我們要實(shí)現(xiàn)一個(gè)簡(jiǎn)單Http服務(wù),進(jìn)行文件的下載,或者進(jìn)行一些其他的操作,例如要發(fā)送郵件,使用HttpListener監(jiān)聽(tīng),處理郵件隊(duì)列,避免在網(wǎng)站上的同步等待。以及獲取一些緩存的數(shù)據(jù)等等行為
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; //文件下載處理請(qǐng)求監(jiān)聽(tīng) private static HttpListener httOtherRequest; //其他超做請(qǐng)求監(jiān)聽(tīng) /// <summary> /// 開(kāi)啟HttpListener監(jiān)聽(tīng) /// </summary> public static void Init() { httpFiledownload = new HttpListener(); //創(chuàng)建監(jiān)聽(tīng)實(shí)例 httpFiledownload.Prefixes.Add("http://10.0.0.217:20009/FileManageApi/Download/"); //添加監(jiān)聽(tīng)地址 注意是以/結(jié)尾。 httpFiledownload.Start(); //允許該監(jiān)聽(tīng)地址接受請(qǐng)求的傳入。 Thread ThreadhttpFiledownload = new Thread(new ThreadStart(GethttpFiledownload)); //創(chuàng)建開(kāi)啟一個(gè)線程監(jiān)聽(tīng)該地址得請(qǐng)求 ThreadhttpFiledownload.Start(); httOtherRequest = new HttpListener(); httOtherRequest.Prefixes.Add("http://10.0.0.217:20009/BehaviorApi/EmailSend/"); //添加監(jiān)聽(tīng)地址 注意是以/結(jié)尾。 httOtherRequest.Start(); //允許該監(jiān)聽(tīng)地址接受請(qǐng)求的傳入。 Thread ThreadhttOtherRequest = new Thread(new ThreadStart(GethttOtherRequest)); ThreadhttOtherRequest.Start(); } /// <summary> /// 執(zhí)行文件下載處理請(qǐng)求監(jiān)聽(tīng)行為 /// </summary> public static void GethttpFiledownload() { while (true) { HttpListenerContext requestContext = httpFiledownload.GetContext(); //接受到新的請(qǐng)求 try { //reecontext 為開(kāi)啟線程傳入的 requestContext請(qǐng)求對(duì)象 Thread subthread = new Thread(new ParameterizedThreadStart((reecontext) => { Console.WriteLine("執(zhí)行文件處理請(qǐng)求監(jiān)聽(tīng)行為"); var request = (HttpListenerContext)reecontext; var image = HttpUtility.UrlDecode(request.Request.QueryString["imgname"]); //接受GET請(qǐng)求過(guò)來(lái)的參數(shù); string filepath = AppDomain.CurrentDomain.BaseDirectory + image; if (!File.Exists(filepath)) { filepath = AppDomain.CurrentDomain.BaseDirectory + "default.jpg"; //下載默認(rèn)圖片 } using (FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read)) { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, (int)fs.Length); //將文件讀到緩存區(qū) 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; //獲取請(qǐng)求流 output.Write(buffer, 0, buffer.Length); //將緩存區(qū)的字節(jié)數(shù)寫入當(dāng)前請(qǐng)求流返回 output.Close(); } })); subthread.Start(requestContext); //開(kāi)啟處理線程處理下載文件 } 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"); //對(duì)客戶端輸出相應(yīng)信息. requestContext.Response.ContentLength64 = buffer.Length; System.IO.Stream output = requestContext.Response.OutputStream; output.Write(buffer, 0, buffer.Length); //關(guān)閉輸出流,釋放相應(yīng)資源 output.Close(); } catch { } } } } /// <summary> /// 執(zhí)行其他超做請(qǐng)求監(jiān)聽(tīng)行為 /// </summary> public static void GethttOtherRequest() { while (true) { HttpListenerContext requestContext = httOtherRequest.GetContext(); //接受到新的請(qǐng)求 try { //reecontext 為開(kāi)啟線程傳入的 requestContext請(qǐng)求對(duì)象 Thread subthread = new Thread(new ParameterizedThreadStart((reecontext) => { Console.WriteLine("執(zhí)行其他超做請(qǐng)求監(jiān)聽(tīng)行為"); var request = (HttpListenerContext)reecontext; var msg = HttpUtility.UrlDecode(request.Request.QueryString["behavior"]); //接受GET請(qǐng)求過(guò)來(lái)的參數(shù); //在此處執(zhí)行你需要進(jìn)行的操作>>比如什么緩存數(shù)據(jù)讀取,隊(duì)列消息處理,郵件消息隊(duì)列添加等等。 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); //開(kāi)啟處理線程處理下載文件 } 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"); //對(duì)客戶端輸出相應(yīng)信息. requestContext.Response.ContentLength64 = buffer.Length; System.IO.Stream output = requestContext.Response.OutputStream; output.Write(buffer, 0, buffer.Length); //關(guān)閉輸出流,釋放相應(yīng)資源 output.Close(); } catch { } } } } } }
調(diào)用方式:注意這里啟動(dòng)程序必須以管理員身份運(yùn)行,因?yàn)樯衔绲谋O(jiān)聽(tīng)需要開(kāi)啟端口,所有需要以管理員身份運(yùn)行。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace HttpListenerApp { class Program { static void Main(string[] args) { //開(kāi)啟請(qǐng)求監(jiān)聽(tīng) HttpProvider.Init(); } } }
執(zhí)行后的結(jié)果為:
這里通過(guò)一個(gè)簡(jiǎn)單的控制程序在里面使用HttpListener實(shí)現(xiàn)了簡(jiǎn)單的Http服務(wù)程序。里面有少量的線程和和異步處理,比如收到行為信息請(qǐng)求可以先返回給用戶,讓用戶不用同步等待,就可以執(zhí)行下一步操作,又比如實(shí)現(xiàn)的簡(jiǎn)單郵件服務(wù)器,將請(qǐng)求發(fā)給HttpListener接收到請(qǐng)求后就立即返回,交給隊(duì)列去發(fā)送郵件。郵件的發(fā)送會(huì)出現(xiàn)延遲等待等情況出現(xiàn),這樣就不用等待。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- 運(yùn)行asp.net時(shí)出現(xiàn) http錯(cuò)誤404-文件或目錄未找到
- Asp.net XMLHTTP封裝類(GET,Post發(fā)送和接收數(shù)據(jù))
- asp.net HttpWebRequest自動(dòng)識(shí)別網(wǎng)頁(yè)編碼
- asp.net 模擬提交有文件上傳的表單(通過(guò)http模擬上傳文件)
- Javascript+XMLHttpRequest+asp.net無(wú)刷新讀取數(shù)據(jù)庫(kù)數(shù)據(jù)
- Flex與.NET互操作 使用FileReference+HttpHandler實(shí)現(xiàn)文件上傳/下載
- asp.net利用HttpModule實(shí)現(xiàn)防sql注入
- ASP,PHP與.NET偽造HTTP-REFERER方法及防止偽造REFERER的方法
- asp.net 客戶端瀏覽器緩存的Http頭介紹
- asp.net通過(guò)HttpModule自動(dòng)在Url地址上添加參數(shù)
相關(guān)文章
ASP.NET實(shí)現(xiàn)偽靜態(tài)網(wǎng)頁(yè)方法小結(jié)
這篇文章主要介紹了ASP.NET實(shí)現(xiàn)偽靜態(tài)網(wǎng)頁(yè)方法小結(jié),主要包括了利用Httphandler實(shí)現(xiàn)URL重寫、地址重寫、利用Mircosoft URLRewriter.dll實(shí)現(xiàn)頁(yè)面?zhèn)戊o態(tài)等,需要的朋友可以參考下2014-09-09.NET下文本相似度算法余弦定理和SimHash淺析及應(yīng)用實(shí)例分析
這篇文章主要介紹了.NET下文本相似度算法余弦定理和SimHash淺析及應(yīng)用,實(shí)例形式詳細(xì)講述了相似度算法余弦定理和SimHash的原理與用法,需要的朋友可以參考下2015-01-01.NET/C#利用反射調(diào)用含ref或out參數(shù)的方法示例代碼
這篇文章主要給大家介紹了關(guān)于.NET/C#利用反射調(diào)用含ref或out參數(shù)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-09-09asp.net+js實(shí)現(xiàn)的ajax sugguest搜索提示效果
阿會(huì)楠根據(jù)網(wǎng)上一份原作者不詳?shù)拇a進(jìn)行了修改,以適合自己的項(xiàng)目并增加了多個(gè)功能。此次放出的代碼為基本實(shí)現(xiàn)代碼,也是最接近原來(lái)的代碼,略去其他功能。版權(quán)歸原作者所有。2009-04-04.NET?6實(shí)現(xiàn)滑動(dòng)驗(yàn)證碼的示例詳解
這篇文章主要為大家詳細(xì)介紹了如何利用.NET?6實(shí)現(xiàn)滑動(dòng)驗(yàn)證碼,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,感興趣的小伙伴可以了解一下2022-11-11Asp.Net實(shí)現(xiàn)FORM認(rèn)證的一些使用技巧(必看篇)
下面小編就為大家?guī)?lái)一篇Asp.Net實(shí)現(xiàn)FORM認(rèn)證的一些使用技巧(必看篇)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-08-08ASP.NET獲取MS SQL Server安裝實(shí)例實(shí)現(xiàn)思路及代碼
在演示中,是把找到的實(shí)例顯示于DropDownList控件中。首先在.aspx拉一個(gè)DropDownList控件,感興趣的朋友可以了解下哦,或許對(duì)你有所幫助2013-01-01