private void TestDynamicAdaptation(DirectoryInfo directory, int port, string ip) { // Поднимем сервер и проверим, удалось ли нам это HttpServer server = TestHelper.UpServer(directory.FullName, port, ip); if (server == null) { ConsoleColorPrinter.WriteLine("Test failed - Server is still down!", ConsoleColor.DarkYellow); return; } // Создадим файл и папку в директории с сайтом (string folder, string html)fileAndFolder = TestHelper.CreateFolderAndHtmlFileWithTestText(directory); if (fileAndFolder.html.Equals(string.Empty)) { ConsoleColorPrinter.WriteLine("Test failed - cannot create test file", ConsoleColor.DarkYellow); } // Подождём, пока адаптируется url Thread.Sleep(2000); // Проверим, доступен ли теперь новый url DirectoryInfo path = new DirectoryInfo(fileAndFolder.folder); if (!TestHelper.IsHttpServerUp(ip, port, 5000, path.Name)) { return; } // Удалим всё то, что создали Directory.Delete(fileAndFolder.folder, true); // Выключим сервер server.Shutdown(); }
private void TestDirectory(DirectoryInfo directory) { // Создадим параметры для сервера int port = 8180; string ip = DefaultArguments.LocalIp; // Поднимем сервер и проверим, удалось ли нам это HttpServer server = TestHelper.UpServer(directory.FullName, port, ip); if (server == null) { ConsoleColorPrinter.WriteLine("Test failed - Server is still down!", ConsoleColor.DarkYellow); return; } if (!directory.FullName.Equals(server.GetWebSiteDirectory())) { ConsoleColorPrinter.WriteLine($"Directories conflict, test failed.\nSetDirectory={directory.FullName}, ServerDirectory={server.GetWebSiteDirectory()}", ConsoleColor.DarkYellow); return; } if (!TestHelper.IsHttpServerUp(ip, port, 5000)) { return; } ConsoleColorPrinter.WriteLine("Test success!", ConsoleColor.DarkYellow); // Выключим сервер server.Shutdown(); }
private void TestUrls() { // Создадим параметры для сервера int port = 8180; string ip = DefaultArguments.LocalIp; string directory = DefaultArguments.DefaultDirectory; // Поднимем сервер и проверим, удалось ли нам это HttpServer server = TestHelper.UpServer(directory, port, ip); if (server == null) { ConsoleColorPrinter.WriteLine("Test failed - Server is still down!", ConsoleColor.DarkYellow); return; } // Получим список всех адресов, которые обслуживает сервер и проверим каждый string[] urls = server.GetActiveUrls(); for (int i = 0; i < urls.Length; i++) { if (!TestHelper.IsHttpServerUp(new Uri(urls[i]), 5000)) { ConsoleColorPrinter.WriteLine($"Error: {urls[i]} is not supporting but must beign", ConsoleColor.DarkYellow); } else { ConsoleColorPrinter.WriteLine($"OK: {urls[i]} is supporting", ConsoleColor.DarkYellow); } } // Выключаем сервер server.Shutdown(); }
/// <summary> /// Выводит минимальную информацию - саму важную - из http запроса. /// </summary> /// <param name="request"></param> public static void PrintMinimalHttpInfo(HttpListenerRequest request) { string[] names = { "UserHostAddress=", "Url=", "RawUrl=", "ProtocolVersion=", "HttpMethod=", "Content-Type=", "Content-Encoding=" }; string[] values = { $"{request.UserHostAddress}", $"{request.Url.OriginalString}", $"{request.RawUrl}", $"{request.ProtocolVersion}", $"{request.HttpMethod}", $"{request.ContentType}", $"{request.ContentEncoding}" }; for (int i = 0; i < names.Length; i++) { ConsoleColorPrinter.Write(names[i], NameColor); ConsoleColorPrinter.WriteLine(values[i], ValueColor); } Console.WriteLine(); }
/// <summary> /// Тест проверяет, правильно ли присвоился порт серверу, и поднялся ли сервер с таким портом. /// </summary> /// <param name="port"></param> private void TestPortAfterCreation(int port) { ConsoleColorPrinter.WriteLine($"Test with data port = {port}\n", ConsoleColor.DarkYellow); // Создадим параметры для сервера string ip = DefaultArguments.LocalIp; string directory = DefaultArguments.DefaultDirectory; // Поднимем сервер и проверим, удалось ли нам это HttpServer server = new HttpServer(ip, port, new DirectoryInfo(directory)); server.StartAsync(); if (port != server.Port) { ConsoleColorPrinter.WriteLine("Ports conflict, test failed", ConsoleColor.DarkYellow); return; } if (!TestHelper.IsHttpServerUp(ip, port, 5000)) { return; } ConsoleColorPrinter.WriteLine("Test success!", ConsoleColor.DarkYellow); // Выключим сервер server.Shutdown(); }
/// <summary> /// Выводит в консоль доступные для подключения URL адреса. /// </summary> /// <param name="httpListener"></param> private void PrintPrefixes(HttpListener httpListener) { ConsoleColorPrinter.WriteLineWithTime("Set next Prefixes:", ConsoleColor.Green, ConsoleColor.Yellow); foreach (string url in httpListener.Prefixes) { ConsoleColorPrinter.WriteLine($"\t{url}", ConsoleColor.Green); } }
public static HttpServer UpServer(string directoryWithSite, int port, string ip) { ConsoleColorPrinter.WriteLine($"Test with data port={port}, ip={ip}, directory={directoryWithSite}\n", ConsoleColor.DarkYellow); HttpServer server = new HttpServer(ip, port, new DirectoryInfo(directoryWithSite)); server.StartAsync(); return(server); }
public void StartTest() { ConsoleColorPrinter.WriteLine("<--- DirectoryInitialisation_Test - Start --->", ConsoleColor.DarkYellow); DirectoryInfo siteDir = new DirectoryInfo(Path.Combine(System.Environment.CurrentDirectory, "WebServer_Test", "TestWebsite")); TestDirectory(siteDir); ConsoleColorPrinter.WriteLine("<--- DirectoryInitialisation_Test - End --->\n", ConsoleColor.DarkYellow); }
public void StartTest() { ConsoleColorPrinter.WriteLine("<--- DirectoryInitialisation_Test - Start --->", ConsoleColor.DarkYellow); DirectoryInfo siteDir = new DirectoryInfo(Path.Combine(System.Environment.CurrentDirectory, "WebServer_Test", "TestWebsite")); int port = 8250; string ip = DefaultArguments.LocalIp; TestDynamicAdaptation(siteDir, port, ip); ConsoleColorPrinter.WriteLine("<--- DirectoryInitialisation_Test - End --->\n", ConsoleColor.DarkYellow); }
public static (string folder, string file) CreateFolderAndHtmlFileWithTestText(DirectoryInfo whereToCreate) { DirectoryInfo tempFolder = null; FileInfo tempHtml = null; try { // Создание папки tempFolder = new DirectoryInfo(Path.Combine(whereToCreate.FullName, "tempFolder")); if (!tempFolder.Exists) { tempFolder.Create(); } // Создание пути к файлу index.html tempHtml = new FileInfo(Path.Combine(tempFolder.FullName, "index.html")); // Небольшая задержка - система наверняка начала обрабатывать появление нового файла Thread.Sleep(500); // Текст для файла string textToFile = "<html><head>Test page</head><body><h1>Bruh<br><h2>Mini bruh</body></html>"; // Запись небольшого текста в файл int magicNum = 0; while (magicNum != 43) { try { File.WriteAllText(tempHtml.FullName, textToFile); magicNum = 43; } catch (Exception) { ConsoleColorPrinter.WriteLineWithTime("File is busy...", ConsoleColor.White, ConsoleColor.Yellow); Thread.Sleep(500); } } return(tempFolder.FullName, tempHtml.FullName); } catch (Exception) { if (tempFolder != null) { if (tempFolder.Exists) { tempFolder.Delete(true); } } return(string.Empty, string.Empty); } }
public void StartTest() { ConsoleColorPrinter.WriteLine("<--- PortInitialisation_Test - Start --->", ConsoleColor.DarkYellow); int port; port = 80; TestPortAfterCreation(port); port = 8150; TestPortAfterCreation(port); ConsoleColorPrinter.WriteLine("<--- PortInitialisation_Test - End --->\n", ConsoleColor.DarkYellow); }
/// <summary> /// Метод инициализирует запуск работы всех модулей программы. /// </summary> private void DoInitialisingOfAllComponents() { // Создание объекта, следящим за указанной директорией и управляющим буфером файлов; загружает файлы в буффер. DirectoryWorker.Start(); // Вывод служебной информации ConsoleColorPrinter.WriteLineWithTime($"Server on [{Dns.GetHostName()}] Started!", ConsoleColor.Green, ConsoleColor.Yellow); // Настройка слушателя http запросов и его запуск. httpListener = this.GetConfiguredListener(); httpListener.Start(); ConsoleColorPrinter.WriteLineWithTime("Start listening requests...\n", ConsoleColor.Green, ConsoleColor.Yellow); }
/// <summary> /// Выводит значения большинства параметров из HttpListenerRequest, /// после чего вызывает вывод значений заголовков HttpListenerRequest.Headers. /// </summary> /// <param name="request"></param> public static void PrintFullHttpRequestText(HttpListenerRequest request) { string[] names = { "IsSecureConnection=", "UserHostAddress=", "UserAgent=", "Url=", "TransportContext=", "ServiceName=", "RawUrl=", "ProtocolVersion=", "UserHostName=", "QueryString=", "UserLanguages=", "HttpMethod=", "UrlReferrer=", "Content-Type=", "Content-Encoding=" }; string[] values = { $"{request.IsSecureConnection}", $"{request.UserHostAddress}", $"{request.UserAgent}", $"{request.Url.OriginalString}", $"{request.TransportContext}", $"{request.ServiceName}", $"{request.RawUrl}", $"{request.ProtocolVersion}", $"{request.UserHostName}", $"{request.QueryString}", $"{string.Join(' ', request.UserLanguages)}", $"{request.HttpMethod}", $"{request.UrlReferrer}", $"{request.ContentType}", $"{request.ContentEncoding}" }; for (int i = 0; i < names.Length; i++) { ConsoleColorPrinter.Write(names[i], NameColor); ConsoleColorPrinter.WriteLine(values[i], ValueColor); } HttpPrinterHelper.PrintFullHeaders(request); }
public static bool IsHttpServerUp(Uri uri, int waitTimeOut) { try { WebRequest request = WebRequest.Create(uri); request.Timeout = waitTimeOut; WebResponse response = request.GetResponse(); ConsoleColorPrinter.WriteLine($"Server by {uri} is up!", ConsoleColor.DarkYellow); return(true); } catch (Exception) { ConsoleColorPrinter.WriteLine($"Server by {uri} is down!", ConsoleColor.DarkYellow); return(false); } }
/// <summary> /// Очистка ресурсов, которые использует объект. Прерываются асинхронные операции, которые делаются на фоне. /// </summary> public void Shutdown() { try { if (httpListener.IsListening) { httpListener.Stop(); //logger.Debug("Listener stopped"); ConsoleColorPrinter.WriteLineWithTime("Listener stopped", ConsoleColor.DarkGreen, ConsoleColor.Yellow); } DirectoryWorker.Shutdown(); //logger.Debug("File system wathcer stopped"); ConsoleColorPrinter.WriteLineWithTime("File system watcher stopped", ConsoleColor.DarkGreen, ConsoleColor.Yellow); NLog.LogManager.Shutdown(); //logger.Debug("Logger stopped"); ConsoleColorPrinter.WriteLineWithTime("Logger stopped", ConsoleColor.DarkGreen, ConsoleColor.Yellow); } catch (Exception) { } }
/// <summary> /// Выводит всё содержимое HttpListener.Headers - т.е. содержимое http протокола /// </summary> /// <param name="request"></param> public static void PrintFullHeaders(HttpListenerRequest request) { ConsoleColorPrinter.Write($"Headers=\n", NameColor); System.Collections.Specialized.NameValueCollection headers = request.Headers; foreach (string key in headers.AllKeys) { ConsoleColorPrinter.WriteLine($"\t{key}:", HeadersNamesColor); string[] textOfKey = headers.GetValues(key); if (textOfKey.Length > 0) { foreach (string text in textOfKey) { ConsoleColorPrinter.WriteLine($"\t\t{text}", HeadersValuesColor); } } else { ConsoleColorPrinter.WriteLine("\t\tThere is no value associated with the header.", HeadersValuesColor); } } }
public void StartTest() { ConsoleColorPrinter.WriteLine("<--- CreatedUrls_Test - Start --->", ConsoleColor.DarkYellow); this.TestUrls(); ConsoleColorPrinter.WriteLine("<--- CreatedUrls_Test - End --->\n", ConsoleColor.DarkYellow); }
static void Main(string[] args) { // Проверка тестового режима if (args.Length == 1) { if (args[0].ToLower().Equals("test")) { EnterPoint.RunTests(); return; } } // Сперва присвоим переменным значения по умолчанию. string ip = DefaultArguments.LocalIp; int port = DefaultArguments.HttpPort; DirectoryInfo directory = new DirectoryInfo(DefaultArguments.DefaultDirectory); // Создание директории по умолчанию на случай, если с ней что-то случилось if (!directory.Exists) { directory.Create(); } // Первый передаваемый аргумент - ip-адрес if (args.Length > 0) { if (IpHelper.IsIPv4(args[0])) { ip = args[0]; } else { Console.WriteLine("Incorrect ip ddress! - Changed for default"); } } // Второй передаваемый аргумент - порт if (args.Length > 1) { int value = 0; if (Int32.TryParse(args[1], out value) & value > 0) { port = value; } else { Console.WriteLine("Incorrect port! - Changed for default"); } } // Третий передаваемый аргумент - папка, где располагается сайт if (args.Length > 2) { DirectoryInfo dir = null; if (DirectoryHelper.TryDirectory(args[2], out dir) & dir.Exists) { directory = dir; } else { Console.WriteLine("Incorrect path to folder or path does not exits! - Changed for default"); } } // Создаём и запускаем HttpServer асинхронно HttpServer ws = new HttpServer(ip, port, directory); ws.StartAsync(); ConsoleColorPrinter.WriteLine("Tip: Press Ctrl + C to finish program or write \"Stop\" to stop server", ConsoleColor.Magenta); while (Console.ReadLine().ToLower() != "stop") { ConsoleColorPrinter.WriteLine("Unknown command!", ConsoleColor.DarkRed); } ; ws.Shutdown(); ConsoleColorPrinter.WriteLine(">> Server was stopped by command from terminal", ConsoleColor.Magenta); }