You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

111 lines
3.4 KiB

  1. #if NETCORE
  2. using System;
  3. using System.Collections.Generic;
  4. using Microsoft.AspNetCore.Http;
  5. using Microsoft.AspNetCore.Hosting;
  6. using Microsoft.Extensions.Hosting;
  7. using Microsoft.Extensions.Configuration;
  8. using Microsoft.Extensions.DependencyInjection;
  9. using Microsoft.AspNetCore.Builder;
  10. using System.Threading.Tasks;
  11. using System.Net;
  12. using System.Security.Cryptography.X509Certificates;
  13. namespace Apewer.Web
  14. {
  15. internal sealed class KestrelStartup
  16. {
  17. public KestrelStartup(IConfiguration configuration)
  18. {
  19. Configuration = configuration;
  20. }
  21. public IConfiguration Configuration { get; }
  22. // 此方法由运行时调用。
  23. // 可使用此方法添加服务到容器。
  24. public void ConfigureServices(IServiceCollection services)
  25. {
  26. // services.AddControllers();
  27. services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  28. }
  29. // 此方法由运行时调用。
  30. // 可使用此方法配置 HTTP 请求命名管道。
  31. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  32. {
  33. if (env.IsDevelopment()) app.UseDeveloperExceptionPage();
  34. var wsOptions = new WebSocketOptions();
  35. wsOptions.KeepAliveInterval = TimeSpan.FromSeconds(20);
  36. app.UseWebSockets(wsOptions);
  37. // WebSocket
  38. //app.Use(async (context, next) =>
  39. //{
  40. // var server = Kestrel.Get(context.Connection.LocalPort);
  41. // if (server != null)
  42. // {
  43. // var wsa = server.WebSocket;
  44. // if (wsa != null)
  45. // {
  46. // if (context.WebSockets.IsWebSocketRequest)
  47. // {
  48. // try
  49. // {
  50. // using (var ws = await context.WebSockets.AcceptWebSocketAsync())
  51. // {
  52. // wsa.Invoke(context, ws);
  53. // }
  54. // }
  55. // catch { }
  56. // }
  57. // }
  58. // }
  59. // await next();
  60. //});
  61. app.Run((context) =>
  62. {
  63. var server = AspNetCore.Get(context.Connection.LocalPort);
  64. if (server == null) return Task.CompletedTask;
  65. var wsa = server.WebSocket;
  66. if (wsa != null && context.WebSockets.IsWebSocketRequest)
  67. {
  68. try
  69. {
  70. using (var ws = context.WebSockets.AcceptWebSocketAsync())
  71. {
  72. wsa.Invoke(context, ws.Result);
  73. }
  74. }
  75. catch { }
  76. return Task.CompletedTask;
  77. }
  78. var a = server.Context;
  79. if (a != null)
  80. {
  81. try
  82. {
  83. a.Invoke(context);
  84. }
  85. catch { }
  86. return Task.CompletedTask;
  87. }
  88. return Task.CompletedTask;
  89. });
  90. // app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); });
  91. }
  92. }
  93. }
  94. #endif