CS2GSI/GSIServer.cs

61 lines
1.9 KiB
C#
Raw Normal View History

2024-01-15 19:33:05 +01:00
using System.Net;
using System.Text;
2024-01-15 20:40:13 +01:00
using Microsoft.Extensions.Logging;
2024-01-15 19:33:05 +01:00
// ReSharper disable LocalizableElement
namespace CS2GSI;
2024-01-15 19:35:57 +01:00
internal class GSIServer
2024-01-15 19:33:05 +01:00
{
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; }
2024-01-15 20:40:13 +01:00
private ILogger? logger;
2024-01-15 19:33:05 +01:00
2024-01-15 20:40:13 +01:00
internal GSIServer(int port, ILogger? logger = null)
2024-01-15 19:33:05 +01:00
{
2024-01-15 20:40:13 +01:00
this.logger = logger;
string prefix = $"http://127.0.0.1:{port}/";
2024-01-15 19:33:05 +01:00
HttpListener = new HttpListener();
2024-01-15 20:40:13 +01:00
HttpListener.Prefixes.Add(prefix);
2024-01-15 19:33:05 +01:00
HttpListener.Start();
2024-01-15 20:40:13 +01:00
this.logger?.Log(LogLevel.Information, $"Listening on {prefix}");
2024-01-15 19:33:05 +01:00
Thread connectionListener = new (HandleConnection);
connectionListener.Start();
IsRunning = true;
}
private async void HandleConnection()
{
while (_keepRunning)
{
HttpListenerContext context = await HttpListener.GetContextAsync();
HttpListenerRequest request = context.Request;
2024-01-15 20:40:13 +01:00
this.logger?.Log(LogLevel.Information, $"[{request.HttpMethod}] {request.Url} - {request.UserAgent}");
2024-01-15 19:33:05 +01:00
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);
2024-01-15 20:40:13 +01:00
this.logger?.Log(LogLevel.Debug, content);
2024-01-15 19:33:05 +01:00
}
HttpListener.Close();
IsRunning = false;
2024-01-15 20:40:13 +01:00
this.logger?.Log(LogLevel.Information, "Stopped GSIServer.");
2024-01-15 19:33:05 +01:00
}
internal void Dispose()
{
2024-01-15 20:40:13 +01:00
this.logger?.Log(LogLevel.Information, "Stopping GSIServer.");
2024-01-15 19:33:05 +01:00
_keepRunning = false;
}
}