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服务器来挂在的程序,

 

posted on 2015-03-11 09:35  無心道(失足程序员)  阅读(4883)  评论(7编辑  收藏  举报