using System; using System.Net; using System.Threading.Tasks; using UnityEngine; // Класс для сериализации в JSON [System.Serializable] public class ServerResponse { public string message; public string timestamp; } public class WebServer : MonoBehaviour { private HttpListener listener; private bool isRunning = true; async void Start() { SettingsManager.Initialize(); await StartWebServerAsync(); } async Task StartWebServerAsync() { listener = new HttpListener(); listener.Prefixes.Add("http://localhost:8080/"); //тест listener.Prefixes.Add("http://fishka:8080/"); // 4. ВСЕ сетевые интерфейсы (самый важный!) listener.Prefixes.Add("http://*:8080/"); listener.Start(); Debug.Log("Async Web сервер запущен"); while (isRunning) { try { var context = await listener.GetContextAsync(); _ = Task.Run(() => ProcessRequestAsync(context)); } catch (System.Exception e) { Debug.LogError($"Ошибка: {e.Message}"); } } } async Task ProcessRequestAsync(HttpListenerContext context) { await Task.Run(() => { try { Debug.Log("Starting SettingsToHtml..."); // Замеряем время выполнения var stopwatch = System.Diagnostics.Stopwatch.StartNew(); // Запускаем в отдельной задаче с таймаутом var htmlTask = Task.Run(() => SettingsToHtml.GetSettingsString(SettingsManager.Container.Settings)); // Ждем максимум 5 секунд if (htmlTask.Wait(TimeSpan.FromSeconds(5))) { string htmlContent = htmlTask.Result; stopwatch.Stop(); Debug.Log($"GetSettingsString выполнился за {stopwatch.ElapsedMilliseconds}ms"); if (string.IsNullOrEmpty(htmlContent)) { htmlContent = "

Error: Method returned empty string

"; } SendHtmlResponse(context, htmlContent); } else { Debug.LogError("GetSettingsString TIMEOUT (5 seconds)!"); SendHtmlResponse(context, "

Error: Settings generation timeout

"); } } catch (Exception ex) { Debug.LogError($"Error in GetSettingsString: {ex.Message}"); SendHtmlResponse(context, $"

Error: {ex.Message}

"); } }); } void SendHtmlResponse(HttpListenerContext context, string html) { byte[] buffer = System.Text.Encoding.UTF8.GetBytes(html); context.Response.ContentType = "text/html; charset=utf-8"; context.Response.ContentLength64 = buffer.Length; context.Response.OutputStream.Write(buffer, 0, buffer.Length); context.Response.OutputStream.Close(); } void OnDestroy() { isRunning = false; listener?.Stop(); listener?.Close(); } private void OnApplicationQuit() { isRunning = false; listener?.Stop(); listener?.Close(); } }