| 引言 | 
此篇是《【輪子狂魔】拋棄IIS,向天借個(gè)HttpListener - 基礎(chǔ)篇(附帶源碼)》的續(xù)篇,也可以說(shuō)是提高篇,如果你對(duì)HttpListener不甚了解的話,建議先看下基礎(chǔ)篇。
這次玩的東西有點(diǎn)多了,大致分為如下幾個(gè)方向:
1.支持靜態(tài)頁(yè)面
2.Ur映射l執(zhí)行方法
3.Url映射執(zhí)行Lua腳本
4.模仿MVC中的C
| 這些東西有什么用? | 
支持靜態(tài)頁(yè)面:這個(gè)純屬玩具吧,只是基礎(chǔ)篇作為引子的一個(gè)簡(jiǎn)單示例而已。
Url映射執(zhí)行方法:類似Web API,可以提供一些基于Http協(xié)議的交互方式。
Url映射執(zhí)行Lua腳本:與上面一樣,不同的是,在某些場(chǎng)景下更合適,比如業(yè)務(wù)頻繁變動(dòng)、頻繁發(fā)布。Lua腳本我就不細(xì)說(shuō)了,不清楚的可以百度一下,是個(gè)很好玩的東西。
模仿MVC中的C:這個(gè)實(shí)例只是想說(shuō)基于HttpListener我們可以做很多事情,如果你對(duì)asp.net、MVC很熟悉,你可以做個(gè)整整的Web Server出來(lái),甚至做個(gè)Web框架都可以。
那么除了這些還可以做什么?
其實(shí)太多了,比如反向代理、負(fù)載均衡、黑名單等等,你都可以做。如果你有興趣可以跟帖討論 ^_^
| 改造HttpServer支持橫向擴(kuò)展 | 
抽離出一個(gè)接口:HttpImplanter

1 interface HttpImplanter2     {3         void Start();4         void Stop();5         void MakeHttpPRefix(HttpListener server);6         ReturnCode ProcessRequest(HttpListenerContext context);7         byte[] CreateReturnResult(HttpListenerContext context, ReturnCode result);8     }View Code改造HttpServer的一些執(zhí)行細(xì)節(jié)

  1 /// <summary>  2     /// 可接收Http請(qǐng)求的服務(wù)器  3     /// </summary>  4     class HttpServer  5     {  6         Thread _httpListenThread;  7   8         /// <summary>  9         /// HttpServer是否已經(jīng)啟動(dòng) 10         /// </summary> 11         volatile bool _isStarted = false; 12  13         /// <summary> 14         /// 線程是否已經(jīng)結(jié)束 15         /// </summary> 16         volatile bool _terminated = false; 17         volatile bool _ready = false; 18         volatile bool _isRuning = false; 19         HttpImplanter _httpImplanter; 20  21         public void Start(HttpImplanter httpImplanter) 22         { 23             if (!HttpListener.IsSupported) 24             { 25                 Logger.Exit("不支持HttpListener!"); 26             } 27  28             if (_isStarted) 29             { 30                 return; 31             } 32             _isStarted = true; 33             _ready = false; 34             _httpImplanter = httpImplanter;  35  36             RunHttpServerThread(); 37  38             while (!_ready) ; 39         } 40  41         private void RunHttpServerThread() 42         { 43             _httpListenThread = new Thread(new ThreadStart(() => 44             { 45                 HttpListener server = new HttpListener(); 46                 try 47                 { 48                     _httpImplanter.MakeHttpPrefix(server); 49                     server.Start(); 50                 } 51                 catch (Exception ex) 52                 { 53                     Logger.Exit("無(wú)法啟動(dòng)服務(wù)器監(jiān)聽(tīng),請(qǐng)檢查網(wǎng)絡(luò)環(huán)境。"); 54                 } 55  56                 _httpImplanter.Start(); 57  58                 IAsyncResult result = null; 59                 while (!_terminated) 60                 { 61                     while (result == null || result.IsCompleted) 62                     { 63                         result = server.BeginGetContext(new AsyncCallback(ProcessHttpRequest), server); 64                     } 65                     _ready = true; 66                     Thread.Sleep(10); 67                 } 68  69                 server.Stop(); 70                 server.Abort(); 71                 server.Close(); 72                 _httpImplanter.Stop(); 73             } 74             )); 75  76             _httpListenThread.IsBackground = true; 77             _httpListenThread.Start(); 78         } 79  80         private void ProcessHttpRequest(IAsyncResult iaServer) 81         { 82             HttpListener server = iaServer.AsyncState as HttpListener; 83             HttpListenerContext context = null; 84             try 85             { 86                 context = server.EndGetContext(iaServer); 87                 Logger.Info("接收請(qǐng)求" + context.Request.Url.ToString()); 88                 //判斷上一個(gè)操作未完成,即返回服務(wù)器正忙,并開(kāi)啟一個(gè)新的異步監(jiān)聽(tīng) 89                 if (_isRuning) 90                 { 91                     Logger.Info("正在處理請(qǐng)求,已忽略請(qǐng)求" + context.Request.Url.ToString()); 92                     RetutnResponse(context, _httpImplanter.CreateReturnResult(context, new ReturnCode((int)CommandResult.ServerIsBusy, EnumHelper.GetEnumDescription(CommandResult.ServerIsBusy)))); 93                     server.BeginGetContext(new AsyncCallback(ProcessHttpRequest), server); 94                     return; 95                 } 96  97                 _isRuning = true; 98                 server.BeginGetContext(new AsyncCallback(ProcessHttpRequest), server); 99             }100             catch101             {102                 Logger.Warning("服務(wù)器已關(guān)閉!");103                 return;104             }105 106             string scriptName = new UrlHelper(context.Request.Url).ScriptName;107             byte[] resultBytes = null;108             if (scriptName.ToLower().EndsWith(".html")||scriptName == "favicon.ico")109             {110                 string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Web", scriptName);111                 if (File.Exists(filePath))112                 {113                     resultBytes = File.ReadAllBytes(filePath);114                 }115                 else116                 {117                     resultBytes = _httpImplanter.CreateReturnResult(context, new ReturnCode((int)CommandResult.FileNotExists, EnumHelper.GetEnumDescription(CommandResult.FileNotExists)));118                 }119             }120             else121             {122                 ReturnCode result = _httpImplanter.ProcessRequest(context);123                 resultBytes = _httpImplanter.CreateReturnResult(context, result);124             }125             RetutnResponse(context, resultBytes);126             _isRuning = false;127         }128 129         private static void RetutnResponse(HttpListenerContext context, byte[] resultBytes)130         {131             context.Response.ContentLength64 = resultBytes.Length;132             System.IO.Stream output = context.Response.OutputStream;133             try134             {135                 output.Write(resultBytes, 0, resultBytes.Length);136                 output.Close();137             }138             catch139             {140                 Logger.Warning("客戶端已經(jīng)關(guān)閉!");141             }142         }143 144         public void Stop()145         {146             if (!_isStarted)147             {148                 return;149             }150 151             _terminated = true;152             _httpListenThread.Join();153 154             _isStarted = false;155         }156 157     }View Code| Url映射執(zhí)行方法 | 
1.繼承HttpImplanter
2.增加監(jiān)聽(tīng)前綴,用于過(guò)濾Url
3.創(chuàng)建返回結(jié)果
3.1 解析Url
3.2 定位訪問(wèn)的類
3.3 執(zhí)行Url所表示的方法
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注