|
- using System;
- using System.IO;
- using System.Net;
- using System.Threading.Tasks;
-
- namespace TBConsole
- {
- public class WebServer
- {
- private bool _running;
- 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;
- switch (context.Request.Url.AbsolutePath)
- {
- case "/command":
- resp = _commandReceiver(request);
- break;
- case "/commands":
- resp = _commandsListSender();
- break;
- default:
- resp = "<img src=\"https://http.cat/404\">";
- break;
- }
- 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);
- var sw = new StreamWriter(context.Response.OutputStream);
- await sw.WriteLineAsync(resp);
- sw.Close();
- }
- catch (Exception e)
- {
- Console.WriteLine(e);
- }
- }
- }
- }
- }
|