跟随上次的socket sever,追加Tcplistener、Httplistener的server
一、Tcplistener搭建web server
1、同socket类似,Tcplistener其实是对socket的封装,方便编程,先初始化tcplistener并且开始监听
1 //初始化端点信息 2 IPAddress address = IPAddress.Loopback; 3 IPEndPoint endPoint = new IPEndPoint(address, 23333); 4 //初始化并启动监听器 5 TcpListener server = new TcpListener(endPoint); 6 server.Start(); 7 Console.WriteLine("Start listening...\n");
2、然后在一个循环中加上监听到的Tcpclient进行相应处理。在这里,与socket不同,Tcplistener将监听到的请求返回成NetworkStream对象
方便程序员编程,使用流的方式进行读写即可
1 while (true) 2 { 3 //挂起并接受请求 4 TcpClient client = server.AcceptTcpClient(); 5 Console.WriteLine("Create a connection."); 6 //获取网络流对象 7 NetworkStream ns = client.GetStream(); 8 //使用utf8转码 9 System.Text.Encoding utf8 =System.Text.Encoding.UTF8; 10 byte[] request = new byte[4096]; 11 int length = ns.Read(request, 0, 4096); 12 string requestString = utf8.GetString(request, 0, length); 13 Console.WriteLine(requestString); 14 15 //初始化状态行 16 string statusLine = "HTTP/1.1 200 OK\r\n"; 17 byte[] statusLineBytes = utf8.GetBytes(statusLine); 18 19 //初始化回应的主体 20 string responseBody = "<html><head><title>From Server</title></head><body><h1>Server Test [TcpListener]</h1></body></html>"; 21 byte[] responseBodyBytes = utf8.GetBytes(responseBody); 22 23 //初始化回应头 24 string responseHeader = string.Format("Content-Type:text/html;charset=utf-8\r\nContent-Length:{0}\r\n", responseBody.Length); 25 byte[] responseHeaderBytes = utf8.GetBytes(responseHeader); 26 27 //回传信息 28 ns.Write(statusLineBytes,0,statusLineBytes.Length); 29 ns.Write(responseHeaderBytes, 0, responseHeaderBytes.Length); 30 ns.Write(new byte[] { 13, 10 }, 0, 2); 31 ns.Write(responseBodyBytes, 0, responseBodyBytes.Length); 32 33 //关闭TcpClient对象,回收资源 34 client.Close(); 35 if (Console.KeyAvailable) 36 break; 37 } 38 server.Stop();
3、至此,web server搭建完成
二、基于HttpListener搭建Web Server
1.在.net命名空间System.Net中提供了HttpListener类,该类使用Http.sys系统组件方可工作,故应先检查系统是否支持。初始化HttpListener对象并开始监听
1 //查看系统是否支持 2 if (!HttpListener.IsSupported) 3 throw new System.InvalidOperationException("Your system must be winXP or Server 2003 or later"); 4 string[] prefixes = new string[] { "http://localhost:23333/" }; 5 6 //初始化HttpListener 7 HttpListener listener = new HttpListener(); 8 foreach (string str in prefixes) 9 listener.Prefixes.Add(str); 10 11 //开启监听 12 listener.Start(); 13 Console.WriteLine("Start listening...\n");
2.调用GetContext获取上下文对象,并从该对象解析出request及response。通过request的诸如HttpMethod,AcceptTypes,UserLanguages,UserAgent,Headers等属性获取请求信息。通过设置response相关属性配置回发的相关信息。使用标准流对象将回应回发出去
1 while (true) 2 { 3 //阻塞线程知道请求到来 4 HttpListenerContext context = listener.GetContext(); 5 //获取请求信息 6 HttpListenerRequest request = context.Request; 7 Console.WriteLine("{0} {1} HTTP/1.1",request.HttpMethod,request.RawUrl); 8 Console.WriteLine("Accept:{0}", string.Join(",", request.AcceptTypes)); 9 Console.WriteLine("Accept-Encoding:{0}", request.Headers["Accept-Encoding"]); 10 11 //获取response对象 12 HttpListenerResponse response = context.Response; 13 //初始化回应主体 14 string responseString = @"<html><head><title>From HttpListener Server</title></head><body><h1>Server Test[HttpListener]</h1></html>"; 15 //初始化回应内容、长度、编码 16 response.ContentLength64 = System.Text.Encoding.UTF8.GetByteCount(responseString); 17 response.ContentType = "text/html;charset=UTF-8"; 18 //输出回应内容 19 System.IO.Stream output = response.OutputStream; 20 System.IO.StreamWriter writer = new System.IO.StreamWriter(output); 21 writer.Write(responseString); 22 //关闭输出流 23 writer.Close(); 24 if (Console.KeyAvailable) 25 break; 26 } 27 listener.Stop();
3.演示完成
If you never take out your hand doing it and just think in your brain and finally you will never get anything.