|
- using System;
- using System.IO;
- using System.Net;
- using System.Threading.Tasks;
-
- namespace TBConsole
- {
- public class WebServer
- {
- public bool Running { get; private set; }
- private readonly HttpListener _listener = new HttpListener();
- private readonly Func<string, string> _commandReceiver;
- private readonly Func<string> _commandsListSender;
-
- public WebServer(Func<string, string> commandReceiver, Func<string> commandsListSender)
- {
- _commandReceiver = commandReceiver;
- _commandsListSender = commandsListSender;
- }
-
- public void Start()
- {
- Running = true;
- KeepListening();
- }
-
- public void Stop()
- {
- Running = false;
- _listener.Stop();
- }
-
- private async void KeepListening()
- {
- _listener.Prefixes.Add("http://localhost:8019/");
- _listener.Start();
- while (Running)
- {
- try
- {
- var context = await _listener.GetContextAsync();
- string request = await new StreamReader(context.Request.InputStream).ReadToEndAsync();
- string resp = context.Request.Url.AbsolutePath switch
- {
- "/command" => _commandReceiver(request),
- "/commands" => _commandsListSender(),
- _ => "<img src=\"https://http.cat/404\">"
- };
- string origin = context.Request.Headers["Origin"];
- if (origin == "http://localhost:4200" || origin == "https://tb-console.web.app")
- context.Response.AddHeader("Access-Control-Allow-Origin", origin);
- await using var sw = new StreamWriter(context.Response.OutputStream);
- await sw.WriteLineAsync(resp);
- }
- catch (ObjectDisposedException)
- {
- }
- catch (Exception e)
- {
- Console.WriteLine(e);
- }
- }
- }
- }
- }
|