using System; using System.Collections.Generic; using System.Net; namespace Model { [ObjectEvent] public class HttpComponentComponentEvent : ObjectEvent, IAwake, ILoad { public void Awake() { this.Get().Awake(); } public void Load() { this.Get().Load(); } } /// /// http请求分发器 /// public class HttpComponent : Component { public AppType appType; public HttpListener listener; public HttpConfig HttpConfig; public Dictionary dispatcher; public void Awake() { StartConfig startConfig = Game.Scene.GetComponent().StartConfig; this.appType = startConfig.AppType; this.HttpConfig = startConfig.GetComponent(); this.Load(); try { this.listener = new HttpListener(); if (this.HttpConfig.Url == null) { this.HttpConfig.Url = ""; } foreach (string s in this.HttpConfig.Url.Split(';')) { if (s.Trim() == "") { continue; } this.listener.Prefixes.Add(s); } this.listener.Start(); this.Accept(); } catch (HttpListenerException e) { throw new Exception($"http server error: {e.ErrorCode}", e); } } public void Load() { this.dispatcher = new Dictionary(); Type[] types = DllHelper.GetMonoTypes(); foreach (Type type in types) { object[] attrs = type.GetCustomAttributes(typeof(HttpHandlerAttribute), false); if (attrs.Length == 0) { continue; } HttpHandlerAttribute httpHandlerAttribute = (HttpHandlerAttribute)attrs[0]; if (!httpHandlerAttribute.AppType.Is(this.appType)) { continue; } object obj = Activator.CreateInstance(type); IHttpHandler ihttpHandler = obj as IHttpHandler; if (ihttpHandler == null) { throw new Exception($"HttpHandler handler not inherit IHttpHandler class: {obj.GetType().FullName}"); } this.dispatcher.Add(httpHandlerAttribute.Path, ihttpHandler); } } public async void Accept() { while (true) { if (this.Id == 0) { return; } HttpListenerContext context = await this.listener.GetContextAsync(); IHttpHandler handler; if (this.dispatcher.TryGetValue(context.Request.Url.AbsolutePath, out handler)) { handler.Handle(context); } //Log.Debug($"{context.Request.Url.AbsolutePath} {context.Request.Url.AbsoluteUri} {context.Request.Url.LocalPath} {context.Request.Url.IdnHost} " + // $"{context.Request.Url.Host} {context.Request.Url.}"); } } public override void Dispose() { if (this.Id == 0) { return; } base.Dispose(); this.listener.Stop(); this.listener.Close(); } } }