基於TcpListener、HttpLister的簡單web 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.演示完成