c#编写一个简单的http服务器

先来张我的帅照哈哈哈

好了不臭美了   上代码

世间万物 只有想不到 没有做不到  哈哈哈  仔细阅读代码     我要凑够 150个字  哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Net;
 6 using System.IO;
 7 
 8 namespace ConsoleApplication1
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14 
15             using (HttpListener listerner = new HttpListener())
16             {
17                 listerner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;//指定身份验证 Anonymous匿名访问
18                 listerner.Prefixes.Add("http://localhost:8080/web/");
19                 listerner.Start();
20                 Console.WriteLine("WebServer Start Successed.......");
21                 while (true)
22                 {
23                     //等待请求连接
24                     //没有请求则GetContext处于阻塞状态
25                     HttpListenerContext ctx = listerner.GetContext();
26                     ctx.Response.StatusCode = 200;//设置返回给客服端http状态代码
27                     string name = ctx.Request.QueryString["name"];
28 
29                     if (name != null)
30                     {
31                         Console.WriteLine(name);
32                     }
33 
34 
35                     //使用Writer输出http响应代码
36                     using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream))
37                     {
38                         Console.WriteLine("hello");
39                         writer.WriteLine("<html><head><title>The WebServer Test</title></head><body>");
40                         writer.WriteLine("<div style=\"height:20px;color:blue;text-align:center;\"><p> hello {0}</p></div>", name);
41                         writer.WriteLine("<ul>");
42 
43                         foreach (string header in ctx.Request.Headers.Keys)
44                         {
45                             writer.WriteLine("<li><b>{0}:</b>{1}</li>", header, ctx.Request.Headers[header]);
46 
47                         }
48                         writer.WriteLine("</ul>");
49                         writer.WriteLine("</body></html>");
50 
51                         writer.Close();
52                         ctx.Response.Close();
53                     }
54 
55                 }
56                 listerner.Stop();
57             }
58         }
59 
60  
61 
62     }
63 }

简不简单 明不明了  哈哈哈  低调 

猜你喜欢

转载自www.cnblogs.com/-jth/p/10639589.html