测试HttpListener监听请求,代码如下:
#region 测试HttpListener /// <summary> /// 测试HttpListener /// </summary> public static async void TestHttpListener() { var threadStart = new Thread(new ThreadStart(StartHttpListener)) { IsBackground = true }; threadStart.Start(); await Task.Delay(TimeSpan.FromSeconds(3)); Console.WriteLine($"开始测试数据"); int test = 1; while (true) { if (test % 2 == 0) { HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create($"http://localhost:5566?a={test}"); httpWebRequest.Method = "Get"; using var response = httpWebRequest.GetResponse().GetResponseStream(); var result = new StreamReader(response).ReadToEnd(); Console.WriteLine($"偶数--结果数据{result}"); } else { HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create($"http://localhost:5566?a={test}"); httpWebRequest.Method = "Post"; var bytes = Encoding.UTF8.GetBytes($"Post数据:{test}"); using var requestStream = httpWebRequest.GetRequestStream(); requestStream.Write(bytes, 0, bytes.Length); requestStream.Flush(); using var response = httpWebRequest.GetResponse().GetResponseStream(); var result = new StreamReader(response).ReadToEnd(); Console.WriteLine($"奇数--结果数据{result}"); } test++; Thread.Sleep(TimeSpan.FromSeconds(2)); } } public static async void StartHttpListener() { await Task.Delay(TimeSpan.FromSeconds(3)); HttpListener httpListener = new HttpListener(); httpListener.Prefixes.Add("http://localhost:5566/"); //httpListener.Prefixes.Add("http://+:5566/"); //httpListener.Prefixes.Add("http://*:5566/"); httpListener.Start(); Console.WriteLine($"httpListener 启动监听"); while (true) { var ssyncResult = httpListener.BeginGetContext(new AsyncCallback(Callback), httpListener); ssyncResult.AsyncWaitHandle.WaitOne(); } } private static void Callback(IAsyncResult ar) { var httplist = (HttpListener)ar.AsyncState; var httpcontent = httplist.EndGetContext(ar); if (httpcontent.Request.HttpMethod == HttpMethod.Post.ToString()) { Console.WriteLine($"请求方法:{httpcontent.Request.HttpMethod}"); var input = new StreamReader(httpcontent.Request.InputStream).ReadToEnd(); var bytes = Encoding.UTF8.GetBytes($"我们收到数据:{input},哈哈哈哈"); httpcontent.Response.OutputStream.Write(bytes, 0, bytes.Length); httpcontent.Response.Close(); } else { Console.WriteLine($"请求方法:{httpcontent.Request.HttpMethod}"); var bytes = Encoding.UTF8.GetBytes($"{httpcontent.Request.RawUrl}----哈哈哈哈"); httpcontent.Response.OutputStream.Write(bytes, 0, bytes.Length); httpcontent.Response.Close(); } } #endregion
测试结果如下:
public class Program /*: MarshalByRefObject*/ { static void Main(string[] args) { #region #region 测试TestHttpListener TestHttpListener(); #endregion Console.Read(); } }