HttpComponent.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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 = StartConfigComponent.Instance.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. List<Type> types = Game.EventSystem.GetTypes(typeof(HttpHandlerAttribute));
  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().Coroutine();
  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 ETVoid Accept()
  146. {
  147. long instanceId = this.InstanceId;
  148. while (true)
  149. {
  150. if (this.InstanceId != instanceId)
  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 ETTask 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 ETTask 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. }