Добавить обработчик POST запроса

This commit is contained in:
_sega 2026-01-26 17:39:32 +03:00
parent 1e6c2f1ce1
commit 2e12ff31a5
2 changed files with 143 additions and 15 deletions

View File

@ -11,6 +11,8 @@ public class SettingsToHtml : MonoBehaviour
StringBuilder sb = new StringBuilder();
sb.AppendLine("Настройки фишки:");
sb.AppendLine("<form action=\"/upd\" method=\"POST\">");
foreach (Setting setting in settings)
{
@ -29,7 +31,8 @@ public class SettingsToHtml : MonoBehaviour
sb.AppendLine($"<p>{setting.Alias}: {GetStringSettingValue(setting)}</p>");
}
}
sb.AppendLine("<input type=\"submit\">");
sb.AppendLine("</form>");
return sb.ToString();
}

View File

@ -1,5 +1,7 @@
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
@ -32,9 +34,7 @@ public class WebServer : MonoBehaviour
// 4. ВСЕ сетевые интерфейсы (самый важный!)
listener.Prefixes.Add("http://*:8080/");
listener.Start();
Debug.Log("Async Web сервер запущен");
while (isRunning)
@ -52,6 +52,35 @@ public class WebServer : MonoBehaviour
}
async Task ProcessRequestAsync(HttpListenerContext context)
{
try
{
string path = context.Request.Url.LocalPath;
string method = context.Request.HttpMethod;
Debug.Log($"Запрос: {method} {path}");
if (method == "GET" && path == "/")
{
await HandleGetSettingsAsync(context);
}
else if (method == "POST" && path == "/upd")
{
await HandlePostUpdateAsync(context);
}
else
{
SendHtmlResponse(context, "<h1>404 Not Found</h1>", 404);
}
}
catch (Exception ex)
{
Debug.LogError($"Error processing request: {ex.Message}");
SendHtmlResponse(context, $"<h1>Error: {ex.Message}</h1>", 500);
}
}
async Task HandleGetSettingsAsync(HttpListenerContext context)
{
await Task.Run(() =>
{
@ -59,14 +88,10 @@ public class WebServer : MonoBehaviour
{
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;
@ -83,24 +108,124 @@ public class WebServer : MonoBehaviour
else
{
Debug.LogError("GetSettingsString TIMEOUT (5 seconds)!");
SendHtmlResponse(context, "<h1>Error: Settings generation timeout</h1>");
SendHtmlResponse(context, "<h1>Error: Settings generation timeout</h1>", 500);
}
}
catch (Exception ex)
{
Debug.LogError($"Error in GetSettingsString: {ex.Message}");
SendHtmlResponse(context, $"<h1>Error: {ex.Message}</h1>");
SendHtmlResponse(context, $"<h1>Error: {ex.Message}</h1>", 500);
}
});
}
void SendHtmlResponse(HttpListenerContext context, string html)
async Task HandlePostUpdateAsync(HttpListenerContext context)
{
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();
try
{
// Читаем тело POST-запроса
string requestBody;
using (var reader = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding))
{
requestBody = await reader.ReadToEndAsync();
}
Debug.Log($"Получен POST запрос на /upd");
Debug.Log($"Тело запроса: {requestBody}");
// Здесь вы можете обработать данные формы
// Обычно данные формы приходят в формате: key1=value1&key2=value2
// Вы можете их разобрать:
var formData = System.Web.HttpUtility.ParseQueryString(requestBody);
// Пример: если у вас есть поле "action" в форме
string action = formData["action"];
string buttonValue = formData["submit"]; // для input type="submit"
Debug.Log($"Action: {action}, Button value: {buttonValue}");
// Пример обработки разных кнопок:
// Если у вас несколько кнопок с разными именами/значениями
if (!string.IsNullOrEmpty(formData["save"]))
{
await HandleSaveAction(formData);
}
else if (!string.IsNullOrEmpty(formData["reset"]))
{
await HandleResetAction(formData);
}
// Отправляем ответ обратно
string responseHtml = @"
<html>
<head><title>Обновлено</title></head>
<body>
<h1>Данные успешно получены!</h1>
<p>Сервер обработал ваш запрос.</p>
<a href='/'>Вернуться назад</a>
<script>
// Через 3 секунды возвращаемся назад
setTimeout(function() {
window.location.href = '/';
}, 3000);
</script>
</body>
</html>";
SendHtmlResponse(context, responseHtml);
}
catch (Exception ex)
{
Debug.LogError($"Error handling POST /upd: {ex.Message}");
SendHtmlResponse(context, $"<h1>Error: {ex.Message}</h1>", 500);
}
}
async Task HandleSaveAction(System.Collections.Specialized.NameValueCollection formData)
{
// Здесь обрабатываем сохранение настроек
Debug.Log("Обработка сохранения настроек...");
// Пример: получаем значения из формы и обновляем настройки
foreach (string key in formData.AllKeys)
{
string value = formData[key];
Debug.Log($"Поле формы: {key} = {value}");
// TODO: Обновить SettingsManager.Container.Settings на основе данных формы
}
// TODO: Сохранить настройки
// SettingsManager.Save();
await Task.CompletedTask;
}
async Task HandleResetAction(System.Collections.Specialized.NameValueCollection formData)
{
// Здесь обрабатываем сброс настроек
Debug.Log("Обработка сброса настроек...");
// TODO: Сбросить настройки к значениям по умолчанию
await Task.CompletedTask;
}
void SendHtmlResponse(HttpListenerContext context, string html, int statusCode = 200)
{
try
{
byte[] buffer = Encoding.UTF8.GetBytes(html);
context.Response.StatusCode = statusCode;
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();
}
catch (Exception ex)
{
Debug.LogError($"Error sending response: {ex.Message}");
}
}
void OnDestroy()