HttpListener的几种用法
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public static void NewMethod1() 2 { 3 HttpListener listener = new HttpListener(); 4 listener.Prefixes.Add(string.Format("http://*:{0}/", 8888)); //添加需要监听的url范围 5 listener.Start(); //开始监听端口,接收客户端请求 6 Console.WriteLine("Listening..."); 7 8 //阻塞主函数至接收到一个客户端请求为止 9 HttpListenerContext context = listener.GetContext(); 10 HttpListenerRequest request = context.Request; 11 HttpListenerResponse response = context.Response; 12 13 string responseString = string.Format("<HTML><BODY> {0}</BODY></HTML>", DateTime.Now); 14 byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); 15 //对客户端输出相应信息. 16 response.ContentLength64 = buffer.Length; 17 System.IO.Stream output = response.OutputStream; 18 output.Write(buffer, 0, buffer.Length); 19 //关闭输出流,释放相应资源 20 Console.WriteLine(Encoding.Default.GetString(buffer)); 21 Console.ReadKey(); 22 output.Close(); 23 24 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 //客户请求处理 2 static void ProcessHttpClient(object obj) 3 { 4 HttpListenerContext context = obj as HttpListenerContext; 5 HttpListenerRequest request = context.Request; 6 HttpListenerResponse response = context.Response; 7 8 //do something as you want 9 string responseString = string.Format("<HTML><BODY> {0}</BODY></HTML>", DateTime.Now); 10 byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); 11 response.ContentLength64 = buffer.Length; 12 System.IO.Stream output = response.OutputStream; 13 output.Write(buffer, 0, buffer.Length); 14 Console.WriteLine(Encoding.Default.GetString(buffer)); 15 //关闭输出流,释放相应资源 16 output.Close(); 17 } 18 19 public static void NewMethod2() 20 { 21 HttpListener listener = new HttpListener(); 22 listener.Prefixes.Add("http://192.168.213.119:9999/"); //要监听的url范围 23 listener.Start(); //开始监听端口,接收客户端请求 24 Console.WriteLine("Listening"); 25 26 try 27 { 28 while (true) 29 { 30 //获取一个客户端请求为止 31 HttpListenerContext context = listener.GetContext(); 32 //将其处理过程放入线程池 33 System.Threading.ThreadPool.QueueUserWorkItem(ProcessHttpClient, context); 34 } 35 } 36 catch (Exception e) 37 { 38 39 Console.WriteLine(e.Message); 40 } 41 finally 42 { 43 listener.Stop(); //关闭HttpListener 44 } 45 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public static void NewMethod3() 2 { 3 HttpListener listener = new HttpListener(); 4 listener.Prefixes.Add("http://localhost/"); //添加需要监听的url范围 5 listener.Start(); //开始监听端口,接收客户端请求 6 Console.WriteLine("Listening..."); 7 8 //阻塞主函数至接收到一个客户端请求为止 9 HttpListenerContext context = listener.GetContext(); 10 HttpListenerRequest request = context.Request; 11 HttpListenerResponse response = context.Response; 12 13 string desUrl = "http://www.google.com"; 14 // string desUrl = "a.txt"; 15 response.Redirect(desUrl); 16 response.OutputStream.Close(); 17 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 static void Method4(object obj) 2 { 3 HttpListenerContext context = obj as HttpListenerContext; 4 HttpListenerRequest request = context.Request; 5 HttpListenerResponse response = context.Response; 6 7 response.ContentType = "application/octet-stream"; 8 9 string fileName = "time.txt"; 10 response.AddHeader("Content-Disposition", "attachment;FileName=" + fileName); 11 12 byte[] data = Encoding.Default.GetBytes(string.Format("当前时间: {0}", DateTime.Now)); 13 response.ContentLength64 = data.Length; 14 System.IO.Stream output = response.OutputStream; 15 output.Write(data, 0, data.Length); 16 output.Close(); 17 } 18 19 public static void NewMethod4() 20 { 21 HttpListener listener = new HttpListener(); 22 listener.Prefixes.Add("http://localhost/"); //要监听的url范围 23 listener.Start(); //开始监听端口,接收客户端请求 24 Console.WriteLine("Listening"); 25 26 try 27 { 28 while (true) 29 { 30 //获取一个客户端请求为止 31 HttpListenerContext context = listener.GetContext(); 32 //将其处理过程放入线程池 33 System.Threading.ThreadPool.QueueUserWorkItem(Method4, context); 34 } 35 } 36 catch (Exception e) 37 { 38 39 Console.WriteLine(e.Message); 40 } 41 finally 42 { 43 listener.Stop(); //关闭HttpListener 44 } 45 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 static void Method5(object obj) 2 { 3 HttpListenerContext context = obj as HttpListenerContext; 4 HttpListenerRequest request = context.Request; 5 HttpListenerResponse response = context.Response; 6 7 FileStream fs = File.OpenRead(@"e:\xmlS.xml"); //待下载的文件 8 9 long startPos = 0; 10 string range = request.Headers["Range"]; 11 bool isResume = string.IsNullOrEmpty(range); 12 if (!isResume) //断点续传请求 13 { 14 //格式bytes=9216- 15 startPos = long.Parse(range.Split('=')[1].Split('-')[0]); 16 response.StatusCode = 206; 17 response.ContentLength64 = fs.Length - startPos; 18 fs.Position = startPos; //设置传送的起始位置 19 } 20 else 21 { 22 response.ContentLength64 = fs.Length; 23 } 24 25 Console.WriteLine("request header"); 26 Console.WriteLine(request.Headers.ToString()); 27 28 response.ContentType = "application/octet-stream"; 29 30 string fileName = "xmlS.xml"; 31 response.AddHeader("Content-Disposition", "attachment;FileName=" + fileName); 32 Stream output = response.OutputStream; 33 34 try 35 { 36 Console.WriteLine("response header"); 37 Console.WriteLine(response.Headers.ToString()); 38 CopyStream(fs, output); //文件传输 39 output.Close(); 40 } 41 catch (HttpListenerException e) //在未写完所有文件时,如果客户端关闭连接,会抛此异常 42 { 43 Console.WriteLine(e.Message); 44 //output.Close(); //如果执行此函数会抛异常在写入所有字节之前不能关闭流。 45 } 46 } 47 48 static void CopyStream(Stream orgStream, Stream desStream) 49 { 50 byte[] buffer = new byte[1024]; 51 52 int read = 0; 53 while ((read = orgStream.Read(buffer, 0, 1024)) > 0) 54 { 55 desStream.Write(buffer, 0, read); 56 57 System.Threading.Thread.Sleep(1000); //模拟慢速设备 58 } 59 } 60 public static void NewMethod5() 61 { 62 HttpListener listener = new HttpListener(); 63 listener.Prefixes.Add("http://localhost/"); //要监听的url范围 64 listener.Start(); //开始监听端口,接收客户端请求 65 Console.WriteLine("Listening"); 66 67 try 68 { 69 while (true) 70 { 71 //获取一个客户端请求为止 72 HttpListenerContext context = listener.GetContext(); 73 //将其处理过程放入线程池 74 System.Threading.ThreadPool.QueueUserWorkItem(Method5, context); 75 } 76 } 77 catch (Exception e) 78 { 79 80 Console.WriteLine(e.Message); 81 } 82 finally 83 { 84 listener.Stop(); //关闭HttpListener 85 } 86 }