首页 > 代码库 > 基于TcpListerer的web服务器 和 基于HttpListerer的web服务器

基于TcpListerer的web服务器 和 基于HttpListerer的web服务器

 摘自《Asp.Net 本质论》作者:郝冠军

/*
为了简化基于TCP协议的监听程序,.NET在System.Net.Sockets命名空间中提供了TcpListerer类,使用它,在构造函数中传递一组网络端点信息就可以准备好监听参数,而不再需要设置使用的网络协议等细节,调用Start方法之后,监听工作开始。AcceptTcpClient方法将阻塞进程,知道一个客户端的连接到达监听器,这个方法将返回一个代表客户端连接的代理对象
*/

 1 class TcpListener_Study
 2 {
 3 public void CreateTcpLister()
 4 {
 5 //获得本机的loopback网络地址,即127.0.0.1
 6 IPAddress address = IPAddress.Loopback;
 7 //创建可以访问的端点,8974 为0表示一个空闲的端口号
 8 IPEndPoint endpoint = new IPEndPoint(address, 8974);
 9 
10 TcpListener newserver = new TcpListener(endpoint);
11 newserver.Start();
12 Console.WriteLine("开始监听,端口号:{0}", endpoint.Port);
13 while (true)
14 {
15 //等待客户端连接
16 TcpClient newclient = newserver.AcceptTcpClient();
17 Console.WriteLine("已建立连接");
18 //得到一个网络流
19 NetworkStream ns = newclient.GetStream();
20 
21 //准被读取客户端请求的数据,读取的数据放在一个数组中
22 byte[] request = new byte[4096];
23 
24 int lentth = ns.Read(request, 0, 4096);
25 
26 string requeststring = Encoding.UTF8.GetString(request, 0, lentth);
27 
28 Console.WriteLine(requeststring);
29 
30 //回应状态行
31 string statusLine = "Http/1.1 200 ok \r\n";
32 byte[] statusLineBytes = Encoding.UTF8.GetBytes(statusLine);
33 //准备发送到客户端的网页
34 string responseBody = "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head runat=\"server\"> <title>Socket Study </title></head><body><form id=\"form1\" runat=\"server\"><div>Hello World ,Socket Study </div> </form></body></html>";
35 byte[] responseBytes = Encoding.UTF8.GetBytes(responseBody);
36 string responseHeader = string.Format("Content-type:text/html; charset=UTF-8 \r\nContent-length:{0}\r\n", responseBody.Length);
37 byte[] responseHeaderBytes = Encoding.UTF8.GetBytes(responseHeader);
38 //向客户端发送状态信息
39 ns.Write(statusLineBytes, 0, statusLineBytes.Length);
40 //发送回应头
41 ns.Write(responseHeaderBytes, 0, statusLineBytes.Length);
42 
43 
44 ns.Write(new byte[] { 13, 10 },0,2);
45 //发送内容
46 ns.Write(responseBytes, 0, statusLineBytes.Length);
47 newclient.Close();
48 if (Console.KeyAvailable)
49 {
50 break;
51 }
52 newserver.Stop();
53 }
54 }
55 }




/* 为了进一步简化http协议的监听器,.Net在命名空间System.Net中提供了HttpListener类,伴随这个对象,.NET提供了一系列相关 * 对象封装了HTTP的处理工作。 * */

 

 

 1 class HttpLisener_Study
 2     {
 3         public void CreateHTTPLister()
 4         {
 5             if (!HttpListener.IsSupported)
 6             {
 7                 throw new System.InvalidOperationException("系统必须为xp sp2 server03 以上版本");
 8             }
 9             string[] prefixes = new string[] { "http://localhost:8974/" };
10 
11             HttpListener listener = new HttpListener();
12             foreach (string  s in prefixes)
13             {
14 
15                 listener.Prefixes.Add(s);
16             }
17             listener.Start();
18             Console.WriteLine("监听中");
19             while (true)
20             {
21                 //阻塞线程,直到请求到达
22                 HttpListenerContext context = listener.GetContext();
23                 Console.WriteLine("已建立连接");
24 
25                 HttpListenerRequest request = context.Request;
26                 Console.WriteLine("{0}{1}  http/1.1", request.HttpMethod, request.RawUrl);
27                 Console.WriteLine("Accept:{0}", string.Join(",", request.AcceptTypes));
28                 Console.WriteLine("Accept-language:{0}",string.Join(",",request.UserLanguages));
29 
30                 Console.WriteLine("User-Agent:{0}", string.Join(",", request.UserAgent));
31 
32                 Console.WriteLine("Accept-Encoding:{0}", string.Join(",", request.Headers["Accept-Encoding"]));
33 
34                 Console.WriteLine("Connection:{0}", request.KeepAlive ? "Keep-Alive" : "close");
35 
36                 Console.WriteLine("Host:{0}", request.UserHostName);
37                 Console.WriteLine("Pragma:{0}", request.Headers["Pragma"]);
38 
39                 //取得回应对象
40                 HttpListenerResponse response = context.Response;
41                 string responseString = "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head runat=\"server\"> <title>Socket Study </title></head><body><form id=\"form1\" runat=\"server\"><div>Hello World ,Socket Study </div> </form></body></html>";
42                 response.ContentLength64 = Encoding.UTF8.GetByteCount(responseString);
43                 response.ContentType = "text/html;charset=UTF-8";
44                 //输出回应内容
45                 System.IO.Stream output = response.OutputStream;
46                 System.IO.StreamWriter writer = new System.IO.StreamWriter(output);
47                 writer.Write(responseString);
48                 writer.Close();
49                 if (Console.KeyAvailable)
50                 {
51                     break;
52                 }
53 
54                 listener.Stop();
55             }
56         }
57     }