HttpComponent.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net;
  5. using System.Reflection;
  6. using System.Text;
  7. namespace ETModel
  8. {
  9. [ObjectSystem]
  10. public class HttpComponentComponentAwakeSystem : AwakeSystem<HttpComponent>
  11. {
  12. public override void Awake(HttpComponent self)
  13. {
  14. self.Awake();
  15. }
  16. }
  17. [ObjectSystem]
  18. public class HttpComponentComponentLoadSystem : LoadSystem<HttpComponent>
  19. {
  20. public override void Load(HttpComponent self)
  21. {
  22. self.Load();
  23. }
  24. }
  25. [ObjectSystem]
  26. public class HttpComponentComponentStartSystem : StartSystem<HttpComponent>
  27. {
  28. public override void Start(HttpComponent self)
  29. {
  30. self.Start();
  31. }
  32. }
  33. /// <summary>
  34. /// http请求分发器
  35. /// </summary>
  36. public class HttpComponent : Entity
  37. {
  38. public HttpListener listener;
  39. public HttpConfig HttpConfig;
  40. public Dictionary<string, IHttpHandler> dispatcher;
  41. // 处理方法
  42. private Dictionary<MethodInfo, IHttpHandler> handlersMapping;
  43. // Get处理
  44. private Dictionary<string, MethodInfo> getHandlers;
  45. private Dictionary<string, MethodInfo> postHandlers;
  46. public void Awake()
  47. {
  48. StartConfig startConfig = StartConfigComponent.Instance.StartConfig;
  49. this.HttpConfig = startConfig.GetComponent<HttpConfig>();
  50. this.Load();
  51. }
  52. public void Load()
  53. {
  54. this.dispatcher = new Dictionary<string, IHttpHandler>();
  55. this.handlersMapping = new Dictionary<MethodInfo, IHttpHandler>();
  56. this.getHandlers = new Dictionary<string, MethodInfo>();
  57. this.postHandlers = new Dictionary<string, MethodInfo>();
  58. HashSet<Type> types = Game.EventSystem.GetTypes(typeof(HttpHandlerAttribute));
  59. foreach (Type type in types)
  60. {
  61. object[] attrs = type.GetCustomAttributes(typeof(HttpHandlerAttribute), false);
  62. if (attrs.Length == 0)
  63. {
  64. continue;
  65. }
  66. HttpHandlerAttribute httpHandlerAttribute = (HttpHandlerAttribute)attrs[0];
  67. object obj = Activator.CreateInstance(type);
  68. IHttpHandler ihttpHandler = obj as IHttpHandler;
  69. if (ihttpHandler == null)
  70. {
  71. throw new Exception($"HttpHandler handler not inherit IHttpHandler class: {obj.GetType().FullName}");
  72. }
  73. this.dispatcher.Add(httpHandlerAttribute.Path, ihttpHandler);
  74. LoadMethod(type, httpHandlerAttribute, ihttpHandler);
  75. }
  76. }
  77. public void Start()
  78. {
  79. try
  80. {
  81. this.listener = new HttpListener();
  82. if (this.HttpConfig.Url == null)
  83. {
  84. this.HttpConfig.Url = "";
  85. }
  86. foreach (string s in this.HttpConfig.Url.Split(';'))
  87. {
  88. if (s.Trim() == "")
  89. {
  90. continue;
  91. }
  92. this.listener.Prefixes.Add(s);
  93. }
  94. this.listener.Start();
  95. this.Accept().Coroutine();
  96. }
  97. catch (HttpListenerException e)
  98. {
  99. throw new Exception($"http server error: {e.ErrorCode}", e);
  100. }
  101. }
  102. public void LoadMethod(Type type, HttpHandlerAttribute httpHandlerAttribute, IHttpHandler httpHandler)
  103. {
  104. // 扫描这个类里面的方法
  105. MethodInfo[] methodInfos = type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.InvokeMethod | BindingFlags.Instance);
  106. foreach (MethodInfo method in methodInfos)
  107. {
  108. object[] getAttrs = method.GetCustomAttributes(typeof(GetAttribute), false);
  109. if (getAttrs.Length != 0)
  110. {
  111. GetAttribute get = (GetAttribute)getAttrs[0];
  112. string path = method.Name;
  113. if (!string.IsNullOrEmpty(get.Path))
  114. {
  115. path = get.Path;
  116. }
  117. getHandlers.Add(httpHandlerAttribute.Path + path, method);
  118. //Log.Debug($"add handler[{httpHandler}.{method.Name}] path {httpHandlerAttribute.Path + path}");
  119. }
  120. object[] postAttrs = method.GetCustomAttributes(typeof(PostAttribute), false);
  121. if (postAttrs.Length != 0)
  122. {
  123. // Post处理方法
  124. PostAttribute post = (PostAttribute)postAttrs[0];
  125. string path = method.Name;
  126. if (!string.IsNullOrEmpty(post.Path))
  127. {
  128. path = post.Path;
  129. }
  130. postHandlers.Add(httpHandlerAttribute.Path + path, method);
  131. //Log.Debug($"add handler[{httpHandler}.{method.Name}] path {httpHandlerAttribute.Path + path}");
  132. }
  133. if (getAttrs.Length == 0 && postAttrs.Length == 0)
  134. {
  135. continue;
  136. }
  137. handlersMapping.Add(method, httpHandler);
  138. }
  139. }
  140. public async ETVoid Accept()
  141. {
  142. long instanceId = this.InstanceId;
  143. while (true)
  144. {
  145. if (this.InstanceId != instanceId)
  146. {
  147. return;
  148. }
  149. HttpListenerContext context = await this.listener.GetContextAsync();
  150. await InvokeHandler(context);
  151. context.Response.Close();
  152. }
  153. }
  154. /// <summary>
  155. /// 调用处理方法
  156. /// </summary>
  157. /// <param name="context"></param>
  158. private async ETTask InvokeHandler(HttpListenerContext context)
  159. {
  160. context.Response.StatusCode = 404;
  161. MethodInfo methodInfo = null;
  162. IHttpHandler httpHandler = null;
  163. string postbody = "";
  164. switch (context.Request.HttpMethod)
  165. {
  166. case "GET":
  167. this.getHandlers.TryGetValue(context.Request.Url.AbsolutePath, out methodInfo);
  168. if (methodInfo != null)
  169. {
  170. this.handlersMapping.TryGetValue(methodInfo, out httpHandler);
  171. }
  172. break;
  173. case "POST":
  174. this.postHandlers.TryGetValue(context.Request.Url.AbsolutePath, out methodInfo);
  175. if (methodInfo != null)
  176. {
  177. this.handlersMapping.TryGetValue(methodInfo, out httpHandler);
  178. using (StreamReader sr = new StreamReader(context.Request.InputStream))
  179. {
  180. postbody = sr.ReadToEnd();
  181. }
  182. }
  183. break;
  184. default:
  185. context.Response.StatusCode = 405;
  186. break;
  187. }
  188. if (httpHandler != null)
  189. {
  190. object[] args = InjectParameters(context, methodInfo, postbody);
  191. // 自动把返回值,以json方式响应。
  192. object resp = methodInfo.Invoke(httpHandler, args);
  193. object result = resp;
  194. if (resp is ETTask<HttpResult> t)
  195. {
  196. await t;
  197. result = t.GetType().GetProperty("Result").GetValue(t, null);
  198. }
  199. if (result != null)
  200. {
  201. using (StreamWriter sw = new StreamWriter(context.Response.OutputStream,Encoding.UTF8))
  202. {
  203. if (result.GetType() == typeof(string))
  204. {
  205. sw.Write(result.ToString());
  206. }
  207. else
  208. {
  209. sw.Write(JsonHelper.ToJson(result));
  210. }
  211. }
  212. }
  213. }
  214. }
  215. /// <summary>
  216. /// 注入参数
  217. /// </summary>
  218. /// <param name="context"></param>
  219. /// <param name="methodInfo"></param>
  220. /// <param name="postbody"></param>
  221. /// <returns></returns>
  222. private static object[] InjectParameters(HttpListenerContext context, MethodInfo methodInfo, string postbody)
  223. {
  224. context.Response.StatusCode = 200;
  225. ParameterInfo[] parameterInfos = methodInfo.GetParameters();
  226. object[] args = new object[parameterInfos.Length];
  227. for (int i = 0; i < parameterInfos.Length; i++)
  228. {
  229. ParameterInfo item = parameterInfos[i];
  230. if (item.ParameterType == typeof(HttpListenerRequest))
  231. {
  232. args[i] = context.Request;
  233. continue;
  234. }
  235. if (item.ParameterType == typeof(HttpListenerResponse))
  236. {
  237. args[i] = context.Response;
  238. continue;
  239. }
  240. try
  241. {
  242. switch (context.Request.HttpMethod)
  243. {
  244. case "POST":
  245. if (item.Name == "postBody") // 约定参数名称为postBody,只传string类型。本来是byte[],有需求可以改。
  246. {
  247. args[i] = postbody;
  248. }
  249. else if (item.ParameterType.IsClass && item.ParameterType != typeof(string) && !string.IsNullOrEmpty(postbody))
  250. {
  251. object entity = JsonHelper.FromJson(item.ParameterType, postbody);
  252. args[i] = entity;
  253. }
  254. break;
  255. case "GET":
  256. string query = context.Request.QueryString[item.Name];
  257. if (query != null)
  258. {
  259. object value = Convert.ChangeType(query, item.ParameterType);
  260. args[i] = value;
  261. }
  262. break;
  263. default:
  264. args[i] = null;
  265. break;
  266. }
  267. }
  268. catch (Exception e)
  269. {
  270. Log.Error(e);
  271. args[i] = null;
  272. }
  273. }
  274. return args;
  275. }
  276. public override void Dispose()
  277. {
  278. if (this.IsDisposed)
  279. {
  280. return;
  281. }
  282. base.Dispose();
  283. this.listener.Stop();
  284. this.listener.Close();
  285. }
  286. }
  287. }