WebHost.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. using System;
  2. using System.Linq;
  3. using System.Net;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using Vinno.FIS.Sonopost.Assets;
  8. using Vinno.FIS.Sonopost.Features.Web;
  9. using Vinno.FIS.Sonopost.Settings;
  10. using Vinno.FIS.Sonopost.WebApi;
  11. using Vinno.IUS.Common.Log;
  12. namespace Vinno.FIS.Sonopost
  13. {
  14. internal class WebHost : IDisposable
  15. {
  16. private bool _isDisposed;
  17. private bool _isHttpRunning;
  18. private bool _isWsRunning;
  19. private HttpListener _httpListener;
  20. private HttpListener _wsListener;
  21. private ViewEngine _viewEngine;
  22. private WebApiEngine _webapiHost;
  23. private WebPreviewHandler _webPreviewHandler;
  24. public WebHost()
  25. {
  26. _viewEngine = new ViewEngine();
  27. _webapiHost = new WebApiEngine();
  28. _webPreviewHandler = new WebPreviewHandler();
  29. }
  30. ~WebHost()
  31. {
  32. DoDispose();
  33. }
  34. /// <summary>
  35. /// Start Http Host
  36. /// </summary>
  37. internal void Start()
  38. {
  39. StartHttp(SonopostSystemSettings.Instance.WebSetting.WebPort, SonopostSystemSettings.Instance.WebSetting.WebPortStandby);
  40. StartWebScocket(SonopostSystemSettings.Instance.WebSetting.WebSocketPort);
  41. }
  42. private void StartHttp(int mainPort, int standbyPort = -1)
  43. {
  44. _httpListener = new HttpListener();
  45. if (CheckPortInUse(mainPort))
  46. {
  47. Logger.WriteLineWarn($"[{nameof(WebHost)}]{nameof(StartHttp)}:Port {mainPort} is occupied.");
  48. return;
  49. }
  50. _httpListener.Prefixes.Add($"http://*:{mainPort}/");
  51. if (standbyPort > -1)
  52. {
  53. if (CheckPortInUse(standbyPort))
  54. {
  55. Logger.WriteLineWarn($"[{nameof(WebHost)}]{nameof(StartHttp)}:Port {standbyPort} is occupied.");
  56. }
  57. else
  58. {
  59. _httpListener.Prefixes.Add($"http://*:{standbyPort}/");
  60. }
  61. }
  62. try
  63. {
  64. _httpListener.Start();
  65. _isHttpRunning = true;
  66. Thread thread = new Thread(new ThreadStart(async () =>
  67. {
  68. while (_isHttpRunning)
  69. {
  70. try
  71. {
  72. HttpListenerContext context = await _httpListener.GetContextAsync();
  73. if (context.Request.IsWebSocketRequest)
  74. {
  75. context.Response.StatusCode = HttpStatusCode.NotFound.GetHashCode();
  76. context.Response.Close();
  77. continue;
  78. }
  79. await HandleRequest(context);
  80. }
  81. catch (Exception ex)
  82. {
  83. Logger.WriteLineError($"[{nameof(WebHost)}]{nameof(StartHttp)} handle context error:{ex}");
  84. }
  85. Thread.Sleep(1);
  86. }
  87. }));
  88. thread.Start();
  89. }
  90. catch (Exception ex)
  91. {
  92. Logger.WriteLineError($"[{nameof(WebHost)}]{nameof(StartHttp)} error:{ex}");
  93. try
  94. {
  95. _httpListener?.Stop();
  96. }
  97. catch { }
  98. }
  99. }
  100. private void StartWebScocket(int port)
  101. {
  102. _wsListener = new HttpListener();
  103. if (CheckPortInUse(port))
  104. {
  105. Logger.WriteLineWarn($"[{nameof(WebHost)}]{nameof(StartWebScocket)}:Port {port} is occupied.");
  106. return;
  107. }
  108. _wsListener.Prefixes.Add($"http://*:{port}/");
  109. try
  110. {
  111. _isWsRunning = true;
  112. _wsListener.Start();
  113. Thread thread = new Thread(new ThreadStart(async () =>
  114. {
  115. while (_isWsRunning)
  116. {
  117. try
  118. {
  119. HttpListenerContext context = await _wsListener.GetContextAsync();
  120. if (context.Request.IsWebSocketRequest)
  121. {
  122. _webPreviewHandler.HandleRequest(context);
  123. }
  124. else
  125. {
  126. context.Response.StatusCode = HttpStatusCode.NotFound.GetHashCode();
  127. context.Response.Close();
  128. }
  129. }
  130. catch (Exception ex)
  131. {
  132. Logger.WriteLineError($"[{nameof(WebHost)}]{nameof(StartWebScocket)} handle context error:{ex}");
  133. }
  134. Thread.Sleep(1);
  135. }
  136. }));
  137. thread.Start();
  138. }
  139. catch (Exception ex)
  140. {
  141. Logger.WriteLineError($"[{nameof(WebHost)}]{nameof(StartWebScocket)} error:{ex}");
  142. try
  143. {
  144. _wsListener?.Stop();
  145. }
  146. catch { }
  147. }
  148. }
  149. /// <summary>
  150. /// Handle Http Request
  151. /// </summary>
  152. /// <param name="context"></param>
  153. /// <returns></returns>
  154. private async Task HandleRequest(HttpListenerContext context)
  155. {
  156. context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
  157. //允许接受跨域身份验证和自定义头
  158. context.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
  159. context.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, Authorization");
  160. if (System.Net.Http.HttpMethod.Get.Method.Equals(context.Request.HttpMethod))
  161. {
  162. await HandleGetRequest(context);
  163. }
  164. else if (System.Net.Http.HttpMethod.Post.Method.Equals(context.Request.HttpMethod))
  165. {
  166. await HandlePostRequest(context);
  167. }
  168. context.Response.Close();
  169. }
  170. /// <summary>
  171. /// 仅限静态资源
  172. /// </summary>
  173. /// <param name="context"></param>
  174. /// <returns></returns>
  175. private async Task HandleGetRequest(HttpListenerContext context)
  176. {
  177. try
  178. {
  179. string url = context.Request.RawUrl.ToLowerInvariant();
  180. #if DEBUG
  181. Logger.WriteLineInfo($"WebHost HandleGetRequest Url:{url}");
  182. #endif
  183. if (url.StartsWith("/download/"))
  184. {
  185. _viewEngine.HandleDownload(context);
  186. }
  187. else
  188. {
  189. byte[] buffer = _viewEngine.FindSource(url);
  190. if (buffer != null)
  191. {
  192. await context.Response.OutputStream.WriteAsync(buffer, 0, buffer.Length);
  193. context.Response.StatusCode = HttpStatusCode.OK.GetHashCode();
  194. }
  195. else
  196. {
  197. context.Response.StatusCode = HttpStatusCode.NotFound.GetHashCode();
  198. }
  199. }
  200. }
  201. catch (Exception ex)
  202. {
  203. Logger.WriteLineError($"[{nameof(WebHost)}]{nameof(HandleGetRequest)} error:{ex}");
  204. context.Response.StatusCode = HttpStatusCode.InternalServerError.GetHashCode();
  205. }
  206. finally
  207. {
  208. context.Response.OutputStream.Flush();
  209. context.Response.OutputStream.Close();
  210. }
  211. }
  212. /// <summary>
  213. /// 仅限WebApi调用
  214. /// </summary>
  215. /// <param name="context"></param>
  216. /// <returns></returns>
  217. private async Task HandlePostRequest(HttpListenerContext context)
  218. {
  219. try
  220. {
  221. string url = context.Request.RawUrl.Split('?')[0].ToLowerInvariant();
  222. Logger.WriteLineInfo($"WebHost HandlePostRequest Url:{url}");
  223. if (url.StartsWith(WebApiEngine.ROUTE_PREFIX))
  224. {
  225. url = url.Substring(WebApiEngine.ROUTE_PREFIX.Length, url.Length - WebApiEngine.ROUTE_PREFIX.Length);
  226. byte[] bodyBytes = new byte[context.Request.ContentLength64];
  227. await context.Request.InputStream.ReadAsync(bodyBytes, 0, bodyBytes.Length);
  228. string requestJson = Encoding.UTF8.GetString(bodyBytes);
  229. string resultJson = _webapiHost.Handle(url, requestJson, context);
  230. if (string.IsNullOrWhiteSpace(resultJson))
  231. {
  232. context.Response.StatusCode = HttpStatusCode.NotFound.GetHashCode();
  233. }
  234. else
  235. {
  236. context.Response.ContentType = "application/json";
  237. context.Response.ContentEncoding = Encoding.UTF8;
  238. byte[] buffer = Encoding.UTF8.GetBytes(resultJson);
  239. await context.Response.OutputStream.WriteAsync(buffer, 0, buffer.Length);
  240. context.Response.StatusCode = HttpStatusCode.OK.GetHashCode();
  241. }
  242. }
  243. else
  244. {
  245. context.Response.StatusCode = HttpStatusCode.NotFound.GetHashCode();
  246. }
  247. }
  248. catch (Exception ex)
  249. {
  250. Logger.WriteLineError($"[{nameof(WebHost)}]{nameof(HandlePostRequest)} error:{ex}");
  251. context.Response.StatusCode = HttpStatusCode.InternalServerError.GetHashCode();
  252. }
  253. finally
  254. {
  255. context.Response.OutputStream.Flush();
  256. context.Response.OutputStream.Close();
  257. }
  258. }
  259. internal void Stop()
  260. {
  261. Logger.WriteLineError($"[{nameof(WebHost)}]Stop Invoke");
  262. _isWsRunning = false;
  263. _isHttpRunning = false;
  264. _wsListener = null;
  265. _httpListener = null;
  266. }
  267. private void DoDispose()
  268. {
  269. if (!_isDisposed)
  270. {
  271. Stop();
  272. _isDisposed = true;
  273. }
  274. }
  275. public void Dispose()
  276. {
  277. DoDispose();
  278. GC.SuppressFinalize(this);
  279. }
  280. /// <summary>
  281. /// 检测端口是否被占用
  282. /// </summary>
  283. /// <param name="port">端口号</param>
  284. /// <returns></returns>
  285. private bool CheckPortInUse(int port)
  286. {
  287. var properties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();
  288. IPEndPoint[] points = properties.GetActiveTcpListeners();
  289. return points?.Any(x => x.Port == port) ?? false;
  290. }
  291. }
  292. }