From fb4dcaf3781527e9e37c04d1c79be0e2606505e8 Mon Sep 17 00:00:00 2001 From: glax Date: Mon, 15 Jan 2024 19:33:05 +0100 Subject: [PATCH] GSIServer --- GSIServer.cs | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 GSIServer.cs diff --git a/GSIServer.cs b/GSIServer.cs new file mode 100644 index 0000000..1af325e --- /dev/null +++ b/GSIServer.cs @@ -0,0 +1,52 @@ +using System.Net; +using System.Text; +// ReSharper disable LocalizableElement + +namespace CS2GSI; + +public class GSIServer +{ + private HttpListener HttpListener { get; init; } + internal delegate void OnMessageEventHandler(string content); + internal event OnMessageEventHandler? OnMessage; + private bool _keepRunning = true; + internal bool IsRunning { get; private set; } + + internal GSIServer(int port) + { + HttpListener = new HttpListener(); + HttpListener.Prefixes.Add($"http://127.0.0.1:{port}/"); + HttpListener.Start(); + + Thread connectionListener = new (HandleConnection); + connectionListener.Start(); + + IsRunning = true; + } + + private async void HandleConnection() + { + while (_keepRunning) + { + HttpListenerContext context = await HttpListener.GetContextAsync(); + HttpListenerRequest request = context.Request; + + Console.WriteLine($"[{request.HttpMethod}] {request.Url} - {request.UserAgent}"); + + HttpResponseMessage responseMessage = new (HttpStatusCode.Accepted); + context.Response.OutputStream.Write(Encoding.UTF8.GetBytes(responseMessage.ToString())); + + StreamReader reader = new (request.InputStream, request.ContentEncoding); + string content = await reader.ReadToEndAsync(); + OnMessage?.Invoke(content); + } + HttpListener.Close(); + IsRunning = false; + } + + internal void Dispose() + { + _keepRunning = false; + } + +} \ No newline at end of file