一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - ASP.NET教程 - .NET下通過HttpListener實現簡單的Http服務

.NET下通過HttpListener實現簡單的Http服務

2020-03-22 18:02Yangyi.He ASP.NET教程

這篇文章主要為大家詳細介紹了.NET下通過HttpListener實現簡單Http服務的相關資料,感興趣的小伙伴們可以參考一下

HttpListener提供一個簡單的、可通過編程方式控制的 HTTP 協議偵聽器.使用它可以很容易的提供一些Http服務,而無需啟動IIS這類大型服務程序。使用HttpListener的方法流程很簡單:主要分為以下幾步 

1.創建一個HTTP偵聽器對象并初始化 

2.添加需要監聽的URI 前綴 

3.開始偵聽來自客戶端的請求 

4.處理客戶端的Http請求 

5.關閉HTTP偵聽器 

例如:我們要實現一個簡單Http服務,進行文件的下載,或者進行一些其他的操作,例如要發送郵件,使用HttpListener監聽,處理郵件隊列,避免在網站上的同步等待。以及獲取一些緩存的數據等等行為 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
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 { }
    }
   }
  }
 }
}

調用方式:注意這里啟動程序必須以管理員身份運行,因為上午的監聽需要開啟端口,所有需要以管理員身份運行。 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace HttpListenerApp
{
 class Program
 {
  static void Main(string[] args)
  {
   //開啟請求監聽
   HttpProvider.Init();
  }
 }
}

執行后的結果為:

.NET下通過HttpListener實現簡單的Http服務

這里通過一個簡單的控制程序在里面使用HttpListener實現了簡單的Http服務程序。里面有少量的線程和和異步處理,比如收到行為信息請求可以先返回給用戶,讓用戶不用同步等待,就可以執行下一步操作,又比如實現的簡單郵件服務器,將請求發給HttpListener接收到請求后就立即返回,交給隊列去發送郵件。郵件的發送會出現延遲等待等情況出現,這樣就不用等待。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 精品久久久久久久久久久 | 俄罗斯性高清完整版 | 国产区成人精品视频 | 国产精品拍拍拍福利在线观看 | 暖暖视频免费观看视频中国.韩剧 | x8x8在线永久免费观看 | 欧美日韩国产一区二区三区欧 | 门房秦大爷在线阅读 | 亚洲aⅴ天堂 | 91精品国产免费久久国语蜜臀 | 欧美一级视频在线高清观看 | 好大好爽好硬 | 美女把小内内脱个精光打屁屁 | 99久久免费国产精品热 | 数学老师扒开腿让我爽快 | 青草午夜精品视频在线观看 | 午夜秀场在线观看 | 国产成人亚洲精品乱码在线观看 | 99久热只有精品视频免费观看17 | 波多野结衣之双方调教在线观看 | 高清在线观看mv的网址免费 | 大乳女子一级毛片 | 国产思妍小仙女一二区 | 国产成人综合久久 | 欧美一区二区三区成人看不卡 | 视频在线观看大片 | 性满足久久久久久久久 | 8mav福利视频 | 毛片免 | 2021海角社区最新版 | 色热综合 | 万域之王在线观看 | 寡妇一级毛片 | 91久久夜色精品国产九色 | 丝瓜视频成人在线观看 | 天天av天天翘天天综合网 | 经典欧美gifxxoo动态图暗网 | 国产精品欧美亚洲韩国日本 | 四虎成人免费观看在线网址 | nxgx国产| 精品一卡2卡3卡4卡5卡亚洲 |