WebHost.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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.Config;
  9. using Vinno.FIS.Sonopost.Features.Web;
  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. if (System.Net.Http.HttpMethod.Get.Method.Equals(context.Request.HttpMethod))
  157. {
  158. await HandleGetRequest(context);
  159. }
  160. else if (System.Net.Http.HttpMethod.Post.Method.Equals(context.Request.HttpMethod))
  161. {
  162. await HandlePostRequest(context);
  163. }
  164. context.Response.Close();
  165. }
  166. /// <summary>
  167. /// 仅限静态资源
  168. /// </summary>
  169. /// <param name="context"></param>
  170. /// <returns></returns>
  171. private async Task HandleGetRequest(HttpListenerContext context)
  172. {
  173. try
  174. {
  175. string url = context.Request.RawUrl.ToLowerInvariant();
  176. if (url.StartsWith("/download/"))
  177. {
  178. _viewEngine.HandleDownload(context);
  179. }
  180. else
  181. {
  182. byte[] buffer = _viewEngine.FindSource(url);
  183. if (buffer != null)
  184. {
  185. await context.Response.OutputStream.WriteAsync(buffer, 0, buffer.Length);
  186. context.Response.StatusCode = HttpStatusCode.OK.GetHashCode();
  187. }
  188. else
  189. {
  190. context.Response.StatusCode = HttpStatusCode.NotFound.GetHashCode();
  191. }
  192. }
  193. }
  194. catch (Exception ex)
  195. {
  196. Logger.WriteLineError($"[{nameof(WebHost)}]{nameof(HandleGetRequest)} error:{ex}");
  197. context.Response.StatusCode = HttpStatusCode.InternalServerError.GetHashCode();
  198. }
  199. finally
  200. {
  201. context.Response.OutputStream.Flush();
  202. context.Response.OutputStream.Close();
  203. }
  204. }
  205. /// <summary>
  206. /// 仅限WebApi调用
  207. /// </summary>
  208. /// <param name="context"></param>
  209. /// <returns></returns>
  210. private async Task HandlePostRequest(HttpListenerContext context)
  211. {
  212. try
  213. {
  214. string url = context.Request.RawUrl.Split('?')[0].ToLowerInvariant();
  215. Logger.WriteLineInfo($"WebHost HandlePostRequest Url:{url}");
  216. if (url.StartsWith(WebApiEngine.ROUTE_PREFIX))
  217. {
  218. url = url.Substring(WebApiEngine.ROUTE_PREFIX.Length, url.Length - WebApiEngine.ROUTE_PREFIX.Length);
  219. byte[] bodyBytes = new byte[context.Request.ContentLength64];
  220. await context.Request.InputStream.ReadAsync(bodyBytes, 0, bodyBytes.Length);
  221. string requestJson = Encoding.UTF8.GetString(bodyBytes);
  222. string resultJson = _webapiHost.Handle(url, requestJson, context);
  223. if (string.IsNullOrWhiteSpace(resultJson))
  224. {
  225. context.Response.StatusCode = HttpStatusCode.NotFound.GetHashCode();
  226. }
  227. else
  228. {
  229. context.Response.ContentType = "application/json";
  230. context.Response.ContentEncoding = Encoding.UTF8;
  231. byte[] buffer = Encoding.UTF8.GetBytes(resultJson);
  232. await context.Response.OutputStream.WriteAsync(buffer, 0, buffer.Length);
  233. context.Response.StatusCode = HttpStatusCode.OK.GetHashCode();
  234. }
  235. }
  236. else
  237. {
  238. context.Response.StatusCode = HttpStatusCode.NotFound.GetHashCode();
  239. }
  240. }
  241. catch (Exception ex)
  242. {
  243. Logger.WriteLineError($"[{nameof(WebHost)}]{nameof(HandlePostRequest)} error:{ex}");
  244. context.Response.StatusCode = HttpStatusCode.InternalServerError.GetHashCode();
  245. }
  246. finally
  247. {
  248. context.Response.OutputStream.Flush();
  249. context.Response.OutputStream.Close();
  250. }
  251. }
  252. internal void Stop()
  253. {
  254. Logger.WriteLineError($"[{nameof(WebHost)}]Stop Invoke");
  255. _isWsRunning = false;
  256. _isHttpRunning = false;
  257. _wsListener = null;
  258. _httpListener = null;
  259. }
  260. private void DoDispose()
  261. {
  262. if (!_isDisposed)
  263. {
  264. Stop();
  265. _isDisposed = true;
  266. }
  267. }
  268. public void Dispose()
  269. {
  270. DoDispose();
  271. GC.SuppressFinalize(this);
  272. }
  273. /// <summary>
  274. /// 检测端口是否被占用
  275. /// </summary>
  276. /// <param name="port">端口号</param>
  277. /// <returns></returns>
  278. private bool CheckPortInUse(int port)
  279. {
  280. var properties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();
  281. IPEndPoint[] points = properties.GetActiveTcpListeners();
  282. return points?.Any(x => x.Port == port) ?? false;
  283. }
  284. }
  285. }