现在把网页服务器的核心处理代码贴出来。
这个代码只是做了基本的处理,对于网站的主页只做了html后缀的识别。
后来我在QFramework中封装的模块做了更多的细节处理。
/// <summary> /// 网页服务器相应处理 /// </summary> /// <param name="ar"></param> private void onWebResponse(IAsyncResult ar) { byte[] responseByte = null; //响应数据 HttpListener httpListener = ar.AsyncState as HttpListener; HttpListenerContext context = httpListener.EndGetContext(ar); //接收到的请求context(一个环境封装体) httpListener.BeginGetContext(new AsyncCallback(onWebResponse), httpListener); //开始 第二次 异步接收request请求 //触发事件 if (OnGetRawContext != null) OnGetRawContext(context); HttpListenerRequest request = context.Request; //接收的request数据 HttpListenerResponse response = context.Response; //用来向客户端发送回复 //触发事件 if (OnGetRequest != null) OnGetRequest(request, response); if (rawUrl == "" || rawUrl == "/") //单纯输入域名或主机IP地址 fileName = WebRoot + @"\index.html"; else if (rawUrl.IndexOf('.') == -1) //不带扩展名,理解为文件夹 fileName = WebRoot + @"\" + rawUrl.SubString(1) + @"\index.html"; else { int fileNameEnd = rawUrl.IndexOf('?'); if (fileNameEnd > -1) fileName = rawUrl.Substring(1, fileNameEnd - 1); fileName = WebRoot + @"\" + rawUrl.Substring(1); } //处理请求文件名的后缀 string fileExt = Path.GetExtension(fileName).Substring(1); if (!File.Exists(fileName)) { responseByte = Encoding.UTF8.GetBytes("404 Not Found!"); response.StatusCode = (int)HttpStatusCode.NotFound; } else { try { responseByte = File.ReadAllBytes(fileName); response.StatusCode = (int)HttpStatusCode.OK; } catch (Exception ex) { Qdb.Error(ex.Message, QDebugErrorType.Error, "onWebResponse"); response.StatusCode = (int)HttpStatusCode.InternalServerError; } } if (MIME_Type.ContainsKey(fileExt)) response.ContentType = MIME_Type[fileExt]; else response.ContentType = MIME_Type["*"]; response.Cookies = request.Cookies; //处理Cookies response.ContentEncoding = Encoding.UTF8;