HttpComponent.cs 11 KB

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