HttpComponent.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net;
  5. using System.Reflection;
  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 (MethodInfo 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. {
  109. path = get.Path;
  110. }
  111. getHandlers.Add(httpHandlerAttribute.Path + path, method);
  112. //Log.Debug($"add handler[{httpHandler}.{method.Name}] path {httpHandlerAttribute.Path + path}");
  113. }
  114. object[] postAttrs = method.GetCustomAttributes(typeof(PostAttribute), false);
  115. if (postAttrs.Length != 0)
  116. {
  117. // Post处理方法
  118. PostAttribute post = (PostAttribute) postAttrs[0];
  119. string path = method.Name;
  120. if (!string.IsNullOrEmpty(post.Path))
  121. {
  122. path = post.Path;
  123. }
  124. postHandlers.Add(httpHandlerAttribute.Path + path, method);
  125. //Log.Debug($"add handler[{httpHandler}.{method.Name}] path {httpHandlerAttribute.Path + path}");
  126. }
  127. if (getAttrs.Length == 0 && postAttrs.Length == 0)
  128. {
  129. continue;
  130. }
  131. handlersMapping.Add(method, httpHandler);
  132. }
  133. }
  134. public async void Accept()
  135. {
  136. while (true)
  137. {
  138. if (this.IsDisposed)
  139. {
  140. return;
  141. }
  142. HttpListenerContext context = await this.listener.GetContextAsync();
  143. InvokeHandler(context);
  144. context.Response.Close();
  145. }
  146. }
  147. /// <summary>
  148. /// 调用处理方法
  149. /// </summary>
  150. /// <param name="context"></param>
  151. private void InvokeHandler(HttpListenerContext context)
  152. {
  153. context.Response.StatusCode = 404;
  154. MethodInfo methodInfo = null;
  155. IHttpHandler httpHandler = null;
  156. string postbody = "";
  157. switch (context.Request.HttpMethod)
  158. {
  159. case "GET":
  160. this.getHandlers.TryGetValue(context.Request.Url.AbsolutePath, out methodInfo);
  161. if (methodInfo != null)
  162. {
  163. this.handlersMapping.TryGetValue(methodInfo, out httpHandler);
  164. }
  165. break;
  166. case "POST":
  167. this.postHandlers.TryGetValue(context.Request.Url.AbsolutePath, out methodInfo);
  168. if (methodInfo != null)
  169. {
  170. this.handlersMapping.TryGetValue(methodInfo, out httpHandler);
  171. using (StreamReader sr = new StreamReader(context.Request.InputStream))
  172. {
  173. postbody = sr.ReadToEnd();
  174. }
  175. }
  176. break;
  177. default:
  178. context.Response.StatusCode = 405;
  179. break;
  180. }
  181. if (httpHandler != null)
  182. {
  183. object[] args = InjectParameters(context, methodInfo, postbody);
  184. // 自动把返回值,以json方式响应。
  185. object resp = methodInfo.Invoke(httpHandler, args);
  186. if (resp != null)
  187. {
  188. using (StreamWriter sw = new StreamWriter(context.Response.OutputStream))
  189. {
  190. if (resp is string)
  191. {
  192. sw.Write(resp.ToString());
  193. }
  194. else
  195. {
  196. sw.Write(JsonHelper.ToJson(resp));
  197. }
  198. }
  199. }
  200. }
  201. }
  202. /// <summary>
  203. /// 注入参数
  204. /// </summary>
  205. /// <param name="context"></param>
  206. /// <param name="methodInfo"></param>
  207. /// <param name="postbody"></param>
  208. /// <returns></returns>
  209. private static object[] InjectParameters(HttpListenerContext context, MethodInfo methodInfo, string postbody)
  210. {
  211. context.Response.StatusCode = 200;
  212. ParameterInfo[] parameterInfos = methodInfo.GetParameters();
  213. object[] args = new object[parameterInfos.Length];
  214. for (int i = 0; i < parameterInfos.Length; i++)
  215. {
  216. ParameterInfo item = parameterInfos[i];
  217. if (item.ParameterType == typeof(HttpListenerRequest))
  218. {
  219. args[i] = context.Request;
  220. }
  221. else if (item.ParameterType == typeof(HttpListenerResponse))
  222. {
  223. args[i] = context.Response;
  224. }
  225. else
  226. {
  227. try
  228. {
  229. if (context.Request.HttpMethod == "POST") //TODO 扩展一些,Http Entity 自动转换 的功能
  230. {
  231. if (item.Name == "postBody") // 约定参数名称为postBody,只传string类型。本来是byte[],有需求可以改。
  232. {
  233. args[i] = postbody;
  234. }
  235. else if (item.ParameterType.IsClass && item.ParameterType != typeof(string) && !string.IsNullOrEmpty(postbody))
  236. {
  237. object entity = JsonHelper.FromJson(item.ParameterType, postbody);
  238. args[i] = entity;
  239. }
  240. }
  241. else if (context.Request.HttpMethod == "GET")
  242. {
  243. string query = context.Request.QueryString[item.Name];
  244. if (query != null)
  245. {
  246. object value = Convert.ChangeType(query, item.ParameterType);
  247. args[i] = value;
  248. }
  249. }
  250. else
  251. {
  252. args[i] = null;
  253. }
  254. }
  255. catch (Exception e)
  256. {
  257. Log.Debug(e.ToString());
  258. args[i] = null;
  259. }
  260. }
  261. }
  262. return args;
  263. }
  264. public override void Dispose()
  265. {
  266. if (this.IsDisposed)
  267. {
  268. return;
  269. }
  270. base.Dispose();
  271. this.listener.Stop();
  272. this.listener.Close();
  273. }
  274. }
  275. }