HttpComponent.cs 7.7 KB

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