程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C# 控制台或者winform程序開啟http的監聽狀態,

C# 控制台或者winform程序開啟http的監聽狀態,

編輯:C#入門知識

C# 控制台或者winform程序開啟http的監聽狀態,



1 public class THttpListener 2 { 3 HttpListener listerner; 4 /// <summary> 5 /// 6 /// </summary> 7 /// <param name="prefixes">格式 http://*/test/ </param> 8 /// <param name="authent"></param> 9 public THttpListener(string[] prefixes, AuthenticationSchemes authent = AuthenticationSchemes.Anonymous) 10 { 11 listerner = new HttpListener(); 12 listerner.AuthenticationSchemes = authent;//指定身份驗證 Anonymous匿名訪問 13 foreach (var item in prefixes) 14 { 15 listerner.Prefixes.Add(item); 16 Console.WriteLine(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + " : HttpListener:" + item); 17 } 18 } 19 20 public delegate void ResponseEventArges(HttpListenerContext ctx); 21 public event ResponseEventArges ResponseEvent; 22 AsyncCallback ac = null; 23 24 public void Start() 25 { 26 if (!listerner.IsListening) 27 { 28 listerner.Start(); 29 ac = new AsyncCallback(GetContextAsyncCallback); 30 listerner.BeginGetContext(ac, null); 31 Console.WriteLine(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + " : Start"); 32 } 33 } 34 35 /// <summary> 36 /// 停止監聽服務 37 /// </summary> 38 public void Stop() 39 { 40 listerner.Stop(); 41 } 42 43 /// <summary> 44 /// 收到監聽請求回調 45 /// </summary> 46 /// <param name="ia"></param> 47 public void GetContextAsyncCallback(IAsyncResult ia) 48 { 49 if (ia.IsCompleted) 50 { 51 var ctx = listerner.EndGetContext(ia); 52 ctx.Response.StatusCode = 200; 53 if (ResponseEvent != null) 54 { 55 ResponseEvent.BeginInvoke(ctx, null, null); 56 } 57 else 58 { 59 System.IO.BinaryWriter br = new System.IO.BinaryWriter(ctx.Response.OutputStream, new UTF8Encoding()); 60 br.Write("error: 服務器未處理"); 61 ctx.Response.Close(); 62 br.Close(); 63 br.Dispose(); 64 } 65 } 66 listerner.BeginGetContext(ac, null); 67 } 68 69 public Dictionary<string, string> getData(System.Net.HttpListenerContext ctx) 70 { 71 var request = ctx.Request; 72 if (request.HttpMethod == "GET") 73 { 74 return getData(ctx, DataType.Get); 75 } 76 else 77 { 78 return getData(ctx, DataType.Post); 79 } 80 } 81 82 public Dictionary<string, string> getData(System.Net.HttpListenerContext ctx, DataType type) 83 { 84 var rets = new Dictionary<string, string>(); 85 var request = ctx.Request; 86 switch (type) 87 { 88 case DataType.Post: 89 if (request.HttpMethod == "POST") 90 { 91 string rawData; 92 using (var reader = new StreamReader(request.InputStream, request.ContentEncoding)) 93 { 94 rawData = reader.ReadToEnd(); 95 } 96 string[] rawParams = rawData.Split('&'); 97 foreach (string param in rawParams) 98 { 99 string[] kvPair = param.Split('='); 100 string key = kvPair[0]; 101 string value = HttpUtility.UrlDecode(kvPair[1]); 102 rets[key] = value; 103 } 104 } 105 break; 106 case DataType.Get: 107 if (request.HttpMethod == "GET") 108 { 109 string[] keys = request.QueryString.AllKeys; 110 foreach (string key in keys) 111 { 112 rets[key] = request.QueryString[key]; 113 } 114 } 115 break; 116 } 117 return rets; 118 } 119 120 /// <summary> 121 /// 數據提交方式 122 /// </summary> 123 public enum DataType 124 { 125 Post, 126 Get, 127 } 128 129 130 }


測試調用類

 

 1 public class TestHttp
 2     {
 3         THttpListener _HttpListener;
 4         public TestHttp()
 5         {
 6             string[] strUrl = new string[] { "http://*/Test/" };
 7             _HttpListener = new THttpListener(strUrl);
 8             _HttpListener.ResponseEvent += _HttpListener_ResponseEvent;
 9             _HttpListener.Start();
10         }
11 
12         void _HttpListener_ResponseEvent(System.Net.HttpListenerContext ctx)
13         {
14             //直接獲取數據
15             Dictionary<string, string> rets = _HttpListener.getData(ctx);
16             //獲取get數據
17             Dictionary<string, string> retGets = _HttpListener.getData(ctx, THttpListener.DataType.Get);
18             //獲取post數據
19             Dictionary<string, string> retPosts = _HttpListener.getData(ctx, THttpListener.DataType.Post);
20             ResponseWrite(ctx.Request.AcceptTypes[0], "Ret", ctx.Response);
21         }
22 
23         static void ResponseWrite(string type, string msg, System.Net.HttpListenerResponse response)
24         {
25             //使用Writer輸出http響應代碼
26             using (System.IO.StreamWriter writer = new System.IO.StreamWriter(response.OutputStream, new UTF8Encoding()))
27             {
28                 response.ContentType = type + ";charset=utf-8";
29                 writer.WriteLine(msg);
30                 writer.Close();
31                 response.Close();
32             }
33         }
34     }


當我們在服務程序或者後台程序需要開啟對http的監聽,來獲取提交數據,但是又不能web服務器來掛在的程序,

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved