/// <summary> /// Handles GET request from client and sends response /// </summary> /// <param name="client"></param> /// <param name="filePath"></param> private static void HandleGetRequest(TcpClient client, string filePath) { // if file path ends with slash (default web page), so it's index.html if (filePath.EndsWith("\\")) { filePath = $"{filePath}index.html"; } // if file doesn't exist - 404 error if (!File.Exists(filePath)) { SendError(client, HttpStatusCodesEnum.NotFoundError); return; } // check extension of the file and make response to client var fileExtension = Regex.Match(filePath, @"(?<extension>\.\w+)").Groups["extension"].Value; var responseContents = string.Empty; switch (fileExtension) { case ".htm": case ".html": responseContents = File.ReadAllText(filePath); break; case ".biis": responseContents = new BiisPage(File.ReadAllText(filePath), Program.Button_OnClick).HtmlPage; break; default: SendError(client, HttpStatusCodesEnum.InternalServerError); break; } // full response to client const int intCode = (int) HttpStatusCodesEnum.Ok; var response = $"HTTP/1.1 {intCode} {GetHttpResponseCodeDescription(HttpStatusCodesEnum.Ok)}\nContent-Type: text/html\nContent-Length: {responseContents.Length}\n\n{responseContents}"; var responseBytes = Encoding.UTF8.GetBytes(response); // send reponse to client client.GetStream().Write(responseBytes, 0, responseBytes.Length); client.Close(); }
/// <summary> /// Handles POST request from client and sends response /// </summary> private static void HandlePostRequest(TcpClient client, string filePath) { // if file doesn't exist - 404 error if (!File.Exists(filePath)) { SendError(client, HttpStatusCodesEnum.NotFoundError); return; } // check extension of file var fileExtension = Regex.Match(filePath, @"(?<extension>\.\w+)").Groups["extension"].Value; BiisPage biisPage; switch (fileExtension) { case ".htm": case ".html": // I'm so tired, I can't implement html handler. Sorry( SendError(client, HttpStatusCodesEnum.InternalServerError); return; case ".biis": biisPage = new BiisPage(File.ReadAllText(filePath), Program.Button_OnClick); break; default: SendError(client, HttpStatusCodesEnum.InternalServerError); return; } var responseContents = biisPage.GetHtmlAfterPost(); const int intCode = (int)HttpStatusCodesEnum.Ok; var response = $"HTTP/1.1 {intCode} {GetHttpResponseCodeDescription(HttpStatusCodesEnum.Ok)}\nContent-Type: text/html\nContent-Length: {responseContents.Length}\n\n{responseContents}"; var responseBytes = Encoding.UTF8.GetBytes(response); // send reponse to client client.GetStream().Write(responseBytes, 0, responseBytes.Length); client.Close(); }