HttpComponent.cs 8.5 KB

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