Web server mod for Techblox to run commands
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

65 wiersze
2.1KB

  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. using System.Threading.Tasks;
  5. namespace TBConsole
  6. {
  7. public class WebServer
  8. {
  9. public bool Running { get; private set; }
  10. private readonly HttpListener _listener = new HttpListener();
  11. private readonly Func<string, string> _commandReceiver;
  12. private readonly Func<string> _commandsListSender;
  13. public WebServer(Func<string, string> commandReceiver, Func<string> commandsListSender)
  14. {
  15. _commandReceiver = commandReceiver;
  16. _commandsListSender = commandsListSender;
  17. }
  18. public void Start()
  19. {
  20. Running = true;
  21. KeepListening();
  22. }
  23. public void Stop()
  24. {
  25. Running = false;
  26. _listener.Stop();
  27. }
  28. private async void KeepListening()
  29. {
  30. _listener.Prefixes.Add("http://localhost:8019/");
  31. _listener.Start();
  32. while (Running)
  33. {
  34. try
  35. {
  36. var context = await _listener.GetContextAsync();
  37. string request = await new StreamReader(context.Request.InputStream).ReadToEndAsync();
  38. string resp = context.Request.Url.AbsolutePath switch
  39. {
  40. "/command" => _commandReceiver(request),
  41. "/commands" => _commandsListSender(),
  42. _ => "<img src=\"https://http.cat/404\">"
  43. };
  44. string origin = context.Request.Headers["Origin"];
  45. if (origin == "http://localhost:4200" || origin == "https://tb-console.web.app")
  46. context.Response.AddHeader("Access-Control-Allow-Origin", origin);
  47. await using var sw = new StreamWriter(context.Response.OutputStream);
  48. await sw.WriteLineAsync(resp);
  49. }
  50. catch (ObjectDisposedException)
  51. {
  52. }
  53. catch (Exception e)
  54. {
  55. Console.WriteLine(e);
  56. }
  57. }
  58. }
  59. }
  60. }