HttpComponent.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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 = StartConfigComponent.Instance.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. List<Type> types = Game.EventSystem.GetTypes(typeof(HttpHandlerAttribute));
  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. long instanceId = this.InstanceId;
  149. while (true)
  150. {
  151. if (this.InstanceId != instanceId)
  152. {
  153. return;
  154. }
  155. HttpListenerContext context = await this.listener.GetContextAsync();
  156. await InvokeHandler(context);
  157. context.Response.Close();
  158. }
  159. }
  160. /// <summary>
  161. /// 调用处理方法
  162. /// </summary>
  163. /// <param name="context"></param>
  164. private async ETTask InvokeHandler(HttpListenerContext context)
  165. {
  166. context.Response.StatusCode = 404;
  167. MethodInfo methodInfo = null;
  168. IHttpHandler httpHandler = null;
  169. string postbody = "";
  170. switch (context.Request.HttpMethod)
  171. {
  172. case "GET":
  173. this.getHandlers.TryGetValue(context.Request.Url.AbsolutePath, out methodInfo);
  174. if (methodInfo != null)
  175. {
  176. this.handlersMapping.TryGetValue(methodInfo, out httpHandler);
  177. }
  178. break;
  179. case "POST":
  180. this.postHandlers.TryGetValue(context.Request.Url.AbsolutePath, out methodInfo);
  181. if (methodInfo != null)
  182. {
  183. this.handlersMapping.TryGetValue(methodInfo, out httpHandler);
  184. using (StreamReader sr = new StreamReader(context.Request.InputStream))
  185. {
  186. postbody = sr.ReadToEnd();
  187. }
  188. }
  189. break;
  190. default:
  191. context.Response.StatusCode = 405;
  192. break;
  193. }
  194. if (httpHandler != null)
  195. {
  196. object[] args = InjectParameters(context, methodInfo, postbody);
  197. // 自动把返回值,以json方式响应。
  198. object resp = methodInfo.Invoke(httpHandler, args);
  199. object result = resp;
  200. if (resp is Task t)
  201. {
  202. await t;
  203. result = t.GetType().GetProperty("Result").GetValue(t, null);
  204. }
  205. if (result != null)
  206. {
  207. using (StreamWriter sw = new StreamWriter(context.Response.OutputStream))
  208. {
  209. if (result.GetType() == typeof(string))
  210. {
  211. sw.Write(result.ToString());
  212. }
  213. else
  214. {
  215. sw.Write(JsonHelper.ToJson(result));
  216. }
  217. }
  218. }
  219. }
  220. }
  221. /// <summary>
  222. /// 注入参数
  223. /// </summary>
  224. /// <param name="context"></param>
  225. /// <param name="methodInfo"></param>
  226. /// <param name="postbody"></param>
  227. /// <returns></returns>
  228. private static object[] InjectParameters(HttpListenerContext context, MethodInfo methodInfo, string postbody)
  229. {
  230. context.Response.StatusCode = 200;
  231. ParameterInfo[] parameterInfos = methodInfo.GetParameters();
  232. object[] args = new object[parameterInfos.Length];
  233. for (int i = 0; i < parameterInfos.Length; i++)
  234. {
  235. ParameterInfo item = parameterInfos[i];
  236. if (item.ParameterType == typeof(HttpListenerRequest))
  237. {
  238. args[i] = context.Request;
  239. continue;
  240. }
  241. if (item.ParameterType == typeof(HttpListenerResponse))
  242. {
  243. args[i] = context.Response;
  244. continue;
  245. }
  246. try
  247. {
  248. switch (context.Request.HttpMethod)
  249. {
  250. case "POST":
  251. if (item.Name == "postBody") // 约定参数名称为postBody,只传string类型。本来是byte[],有需求可以改。
  252. {
  253. args[i] = postbody;
  254. }
  255. else if (item.ParameterType.IsClass && item.ParameterType != typeof(string) && !string.IsNullOrEmpty(postbody))
  256. {
  257. object entity = JsonHelper.FromJson(item.ParameterType, postbody);
  258. args[i] = entity;
  259. }
  260. break;
  261. case "GET":
  262. string query = context.Request.QueryString[item.Name];
  263. if (query != null)
  264. {
  265. object value = Convert.ChangeType(query, item.ParameterType);
  266. args[i] = value;
  267. }
  268. break;
  269. default:
  270. args[i] = null;
  271. break;
  272. }
  273. }
  274. catch (Exception e)
  275. {
  276. Log.Error(e);
  277. args[i] = null;
  278. }
  279. }
  280. return args;
  281. }
  282. public override void Dispose()
  283. {
  284. if (this.IsDisposed)
  285. {
  286. return;
  287. }
  288. base.Dispose();
  289. this.listener.Stop();
  290. this.listener.Close();
  291. }
  292. }
  293. }