HttpComponentSystem.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. namespace ET.Server
  5. {
  6. [EntitySystemOf(typeof(HttpComponent))]
  7. public static partial class HttpComponentSystem
  8. {
  9. [EntitySystem]
  10. private static void Awake(this HttpComponent self, string address)
  11. {
  12. try
  13. {
  14. self.Listener = new HttpListener();
  15. foreach (string s in address.Split(';'))
  16. {
  17. if (s.Trim() == "")
  18. {
  19. continue;
  20. }
  21. self.Listener.Prefixes.Add(s);
  22. }
  23. self.Listener.Start();
  24. self.Accept().Coroutine();
  25. }
  26. catch (HttpListenerException e)
  27. {
  28. throw new Exception($"请先在cmd中运行: netsh http add urlacl url=http://*:你的address中的端口/ user=Everyone, address: {address}", e);
  29. }
  30. }
  31. [EntitySystem]
  32. private static void Destroy(this HttpComponent self)
  33. {
  34. self.Listener.Stop();
  35. self.Listener.Close();
  36. }
  37. private static async ETTask Accept(this HttpComponent self)
  38. {
  39. long instanceId = self.InstanceId;
  40. while (self.InstanceId == instanceId)
  41. {
  42. try
  43. {
  44. HttpListenerContext context = await self.Listener.GetContextAsync();
  45. self.Handle(context).Coroutine();
  46. }
  47. catch (ObjectDisposedException)
  48. {
  49. }
  50. catch (Exception e)
  51. {
  52. Log.Error(e);
  53. }
  54. }
  55. }
  56. private static async ETTask Handle(this HttpComponent self, HttpListenerContext context)
  57. {
  58. try
  59. {
  60. IHttpHandler handler = HttpDispatcher.Instance.Get(self.IScene.SceneType, context.Request.Url.AbsolutePath);
  61. await handler.Handle(self.Scene(), context);
  62. }
  63. catch (Exception e)
  64. {
  65. Log.Error(e);
  66. }
  67. context.Request.InputStream.Dispose();
  68. context.Response.OutputStream.Dispose();
  69. }
  70. }
  71. }