// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime applicationLifetime, ILogger <Startup> logger, ILoggerFactory loggerFactory, IServiceProvider serviceProvider) { _logger = logger; _logger.LogInformation("Running in ({0}) environment", env.EnvironmentName); loggerFactory.AddProvider(serviceProvider.GetService <PickemDatabaseLoggerProvider>()); app.UseAuthentication(); // JSON output exception output app.UseMiddleware(typeof(JsonOutputErrorHandlingMiddleware)); app.UseStaticFiles(); var webSocketOptions = new WebSocketOptions() { KeepAliveInterval = TimeSpan.FromSeconds(Consts.WEB_SOCKET_KEEP_ALIVE_SECONDS), ReceiveBufferSize = Consts.WEB_SOCKET_BUFFER_SIZE }; app.UseWebSockets(webSocketOptions); app.UseMiddleware <SuperWebSocketMiddleware>(); // allow requests from any origin app.UseCors(builder => { builder.AllowAnyOrigin(); builder.AllowAnyMethod(); builder.AllowAnyHeader(); }); app.UseMvc(); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Pickem API"); }); applicationLifetime.ApplicationStarted.Register(OnApplicationStarted); applicationLifetime.ApplicationStopping.Register(OnApplicationStopping); }
public async Task ServerGracefullyClosesWhenClientSendsCloseFrameThenApplicationEnds() { using (StartVerifiableLog()) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new HttpConnectionContext("foo", connectionToken: null, LoggerFactory.CreateLogger(nameof(HttpConnectionContext))) { Transport = pair.Transport, Application = pair.Application, }; using (var feature = new TestWebSocketConnectionFeature()) { var options = new WebSocketOptions { // We want to verify behavior without timeout affecting it CloseTimeout = TimeSpan.FromSeconds(20) }; var connectionContext = new HttpConnectionContext(string.Empty, null, null); var ws = new WebSocketsServerTransport(options, connection.Application, connectionContext, LoggerFactory); var serverSocket = await feature.AcceptAsync(); // Give the server socket to the transport and run it var transport = ws.ProcessSocketAsync(serverSocket); // Run the client socket var client = feature.Client.ExecuteAndCaptureFramesAsync(); await feature.Client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None).OrTimeout(); // close the client to server channel connection.Transport.Output.Complete(); _ = await client.OrTimeout(); await transport.OrTimeout(); Assert.Equal(WebSocketCloseStatus.NormalClosure, serverSocket.CloseStatus); } } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { var fordwardedHeaderOptions = new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }; fordwardedHeaderOptions.KnownNetworks.Clear(); fordwardedHeaderOptions.KnownProxies.Clear(); app.UseForwardedHeaders(fordwardedHeaderOptions); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } var webSocketOptions = new WebSocketOptions() { KeepAliveInterval = TimeSpan.FromSeconds(120), ReceiveBufferSize = 4 * 1024 }; app.UseRouting(); app.UseWebSockets(webSocketOptions); app.UseAuthentication(); app.UseAuthorization(); app.UseStaticFiles(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); app.Run(async(context) => { await context.Response.WriteAsync("Could Not Find Anything"); }); }
public static IApplicationBuilder UseWebNotify(this IApplicationBuilder app, EventHandler <WebNotifyEventArgs> removeHandler = null) { var service = app.ApplicationServices.GetService <WebNotifyService>(); service.Login(null); if (removeHandler != null) { service.RemoveClient += removeHandler; } var webSocketOptions = new WebSocketOptions() { KeepAliveInterval = TimeSpan.FromSeconds(100), ReceiveBufferSize = 8 * 1024 }; app.UseWebSockets(webSocketOptions); return(app); }
private void BuildHandler() { var be = _serviceDispatcher.Binding.CreateBindingElements(); var mebe = be.Find <MessageEncodingBindingElement>(); if (mebe == null) { throw new ArgumentException("Must provide a MessageEncodingBindingElement", nameof(_serviceDispatcher.Binding)); } var tbe = be.Find <HttpTransportBindingElement>(); if (tbe == null) { throw new ArgumentException("Must provide a HttpTransportBindingElement", nameof(_serviceDispatcher.Binding)); } var httpSettings = new HttpTransportSettings(); httpSettings.BufferManager = BufferManager.CreateBufferManager(DefaultMaxBufferPoolSize, tbe.MaxBufferSize); httpSettings.OpenTimeout = _serviceDispatcher.Binding.OpenTimeout; httpSettings.ReceiveTimeout = _serviceDispatcher.Binding.ReceiveTimeout; httpSettings.SendTimeout = _serviceDispatcher.Binding.SendTimeout; httpSettings.CloseTimeout = _serviceDispatcher.Binding.CloseTimeout; httpSettings.MaxBufferSize = tbe.MaxBufferSize; httpSettings.MaxReceivedMessageSize = tbe.MaxReceivedMessageSize; httpSettings.MessageEncoderFactory = mebe.CreateMessageEncoderFactory(); httpSettings.ManualAddressing = tbe.ManualAddressing; httpSettings.TransferMode = tbe.TransferMode; httpSettings.KeepAliveEnabled = tbe.KeepAliveEnabled; httpSettings.AnonymousUriPrefixMatcher = new HttpAnonymousUriPrefixMatcher(); httpSettings.AuthenticationScheme = tbe.AuthenticationScheme; httpSettings.WebSocketSettings = tbe.WebSocketSettings.Clone(); _httpSettings = httpSettings; WebSocketOptions = CreateWebSocketOptions(tbe); if (WebSocketOptions == null) { _replyChannel = new AspNetCoreReplyChannel(_servicesScopeFactory.CreateScope().ServiceProvider, _httpSettings); _replyChannelDispatcherTask = _serviceDispatcher.CreateServiceChannelDispatcherAsync(_replyChannel); } }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { var webSocketOptions = new WebSocketOptions() { KeepAliveInterval = TimeSpan.FromSeconds(120), ReceiveBufferSize = 4 * 1024 }; app.UseWebSockets(webSocketOptions); app.Use(async(context, next) => { if (context.Request.Path == "/ws") { if (context.WebSockets.IsWebSocketRequest) { WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(); await Echo(context, webSocket); } else { context.Response.StatusCode = 400; } } else { await next(); } }); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseStaticFiles(); app.UseMvc(); }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); var webSocketOptions = new WebSocketOptions() { KeepAliveInterval = Settings.KeepAliveInterval, ReceiveBufferSize = Settings.ReceiveBufferSize }; app.UseWebSockets(webSocketOptions); app.UseMiddleware <SocketMiddleware>(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } var webSocketOptions = new WebSocketOptions() { KeepAliveInterval = TimeSpan.FromSeconds(120), ReceiveBufferSize = 4 * 1024 }; app.UseWebSockets(webSocketOptions); app.Use(async(context, next) => { if (context.Request.Path == "/ws") { if (context.WebSockets.IsWebSocketRequest) { WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(); await Console.WriteLine(context + " " + webSocket); } else { context.Response.StatusCode = 400; } } else { await next(); } }); // app.UseHttpsRedirection(); app.UseMvc(); }
public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseWebSockets(); // app.useSt(); // For the wwwroot folder app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider( "F:\\MyProject\\VRPWithZhangkun\\MainApp\\VRPWithZhangkun\\VRPServer\\WebApp\\webHtml"), RequestPath = "/StaticFiles" }); //app.Map("/postinfo", HandleMapdownload); var webSocketOptions = new WebSocketOptions() { KeepAliveInterval = TimeSpan.FromSeconds(60000 * 1000), ReceiveBufferSize = 1024 * 1000 }; app.UseWebSockets(webSocketOptions); // app.Map("/websocket", WebSocket); app.Map("/websocket", builder => { builder.Use(async(context, next) => { if (context.WebSockets.IsWebSocketRequest) { { // Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}--累计登陆{sumVisitor},当前在线{sumVisitor - sumLeaver}"); var webSocket = await context.WebSockets.AcceptWebSocketAsync(); await Echo(webSocket); } } await next(); }); }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } var webSocketOptions = new WebSocketOptions() { KeepAliveInterval = TimeSpan.FromSeconds(120), ReceiveBufferSize = 4 * 1024 }; app.UseWebSockets(webSocketOptions); app.Use(async(context, next) => { if (context.Request.Path == "/ws") { if (context.WebSockets.IsWebSocketRequest) { WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(); list.Add(webSocket); await Echo(context, webSocket); } else { context.Response.StatusCode = 400; } } else { await next(); } }); app.UseHttpsRedirection(); app.UseMvc(); }
private static void RegisterWSProtocol(ContainerBuilderWrapper builder, WebSocketOptions options) { builder.Register(provider => { return(new DefaultWSServerMessageListener(provider.Resolve <ILogger <DefaultWSServerMessageListener> >(), provider.Resolve <IWSServiceEntryProvider>(), options )); }).SingleInstance(); builder.Register(provider => { var messageListener = provider.Resolve <DefaultWSServerMessageListener>(); return(new WSServiceHost(async endPoint => { await messageListener.StartAsync(endPoint); return messageListener; })); }).As <IServiceHost>(); }
public static void UseRazorComponentsRuntimeCompilation(this IApplicationBuilder app) { var webSocketOptions = new WebSocketOptions() { KeepAliveInterval = TimeSpan.FromSeconds(120), ReceiveBufferSize = 4 * 1024 }; webSocketOptions.AllowedOrigins.Add("https://localhost:5001"); webSocketOptions.AllowedOrigins.Add("https://localhost:5000"); webSocketOptions.AllowedOrigins.Add("http://localhost:5000"); app.UseWebSockets(webSocketOptions); var runtimeComponentsGenerator = new RuntimeComponentsGenerator(_serviceCollection); var firstTimeRender = runtimeComponentsGenerator.FirstTimeRender(); runtimeComponentsGenerator.AddRazorStaticRuntimeGeneration(); app.Use(async(context, next) => { if (context.Request.Path == "/preview") { await context.Response.WriteAsync(firstTimeRender); } else if (context.Request.Path == "/ws") { if (context.WebSockets.IsWebSocketRequest) { WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(); runtimeComponentsGenerator.AttachWebsocket(webSocket); await KeepAlive(context, webSocket); } else { context.Response.StatusCode = 400; } } else { await next(); } }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { InitializeContainer(app); container.Verify(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); if (UsingInMemoryDb(app)) { ClearRedisCache(); } } app.UseMiddleware <ErrorHandlingMiddleware>(); app.UseAuthentication(); app.UseCors("MyPolicy"); var webSocketOptions = new WebSocketOptions() { KeepAliveInterval = TimeSpan.FromSeconds(120), ReceiveBufferSize = 4 * 1024, }; app.UseWebSockets(webSocketOptions); app.UseSignalR(routes => { routes.MapHub <FileContentChangedNotificationHub>("/contentChangesHub"); }); app.UseMiddleware <WebSocketsMiddleware>(container); var webSocketHandlerRegistry = container.GetInstance <IWebSocketHandlerRegistrar>(); var webSocketHandler = container.GetInstance <IWebSocketHandler <CurrentLockNotificationsSubscriptionMessage> >(); webSocketHandlerRegistry.RegisterHandler("/ws/fileLocks", webSocketHandler); app.UseMvc(); container.GetInstance <EventDispatcher>().SubscribeToEvents(); container.GetInstance <UsersIntegrationService>().Run(); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, System.IServiceProvider serviceProvider) { app.UseCors("MyPolicy"); app.UseDefaultFiles(); app.UseStaticFiles(); if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); // todo : removee app.UseMiddleware(typeof(Utils.ErrorHandlingMiddleware)); } else { app.UseMiddleware(typeof(Utils.ErrorHandlingMiddleware)); } var wsOptions = new WebSocketOptions() { KeepAliveInterval = System.TimeSpan.FromSeconds(60), ReceiveBufferSize = 4 * 1024 }; app.UseWebSockets(wsOptions); app.MapWebSocketManager(Configuration["Params:WebSocketPath"], serviceProvider.GetService <WebSocketRouter>()); app.UseSwagger(c => { c.RouteTemplate = "api-docs/{documentName}/swagger.json"; }); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/api-docs/v1/swagger.json", "MPGP API V1"); c.RoutePrefix = string.Empty; }); app.UseMvc(routes => { routes.MapRoute("default", "{controller}/{id?}"); }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); var webSocketOptions = new WebSocketOptions() { KeepAliveInterval = TimeSpan.FromSeconds(120), ReceiveBufferSize = 4 * 1024 }; app.UseWebSockets(webSocketOptions); app.Use(async(context, next) => { if (context.Request.Path == "/ws") { if (context.WebSockets.IsWebSocketRequest) { using (WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync()) { await HandleWebsocketConnectionAsync(context, webSocket); } } else { context.Response.StatusCode = 400; } } else { await next(); } }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime, IServiceProvider serviceProvider) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", appName + "V1"); }); app.UseSession(); app.UseMvc(); var webSocketOptions = new WebSocketOptions() { KeepAliveInterval = TimeSpan.FromSeconds(120), ReceiveBufferSize = 4 * 1024 }; app.UseWebSockets(webSocketOptions); app.MapWebSocketManager("/ws", serviceProvider.GetService <CSChatHandler>()); app.UseFileServer(); lifetime.ApplicationStarted.Register(() => { app.ApplicationServices.GetService <ActorSystem>(); // start Akka.NET }); lifetime.ApplicationStopping.Register(() => { app.ApplicationServices.GetService <ActorSystem>().Terminate().Wait(); }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider) { app.UseSession(); app.UseAuthentication(); app.UseMiddleware <IotHubManagerMiddleware>(serviceProvider.GetService <IotHubApiHandler>()); //新規追加:Microsoft.AspNetCore.WebSockets var webSocketOptions = new WebSocketOptions() { KeepAliveInterval = TimeSpan.FromSeconds(WebSocketManagerMiddleware.KEEP_ALIVE_INTERVAL), ReceiveBufferSize = WebSocketManagerMiddleware.BUFFER_SIZE }; app.UseWebSockets(webSocketOptions); //app.MapWebSocketManager("/ws", serviceProvider.GetService<TestMessageHandler>()); // WebSocketAPI app.MapWebSocketManager("/wsapi", serviceProvider.GetService <WebSocketApiHandler>()); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Users}/{action=Login}"); }); // Set up custom content types - associating file extension to MIME type var provider = new FileExtensionContentTypeProvider(); // Replace an existing mapping provider.Mappings[".ttf"] = "application/x-font-ttf"; app.UseDefaultFiles(); app.UseStaticFiles(new StaticFileOptions { ContentTypeProvider = provider }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseDeveloperExceptionPage(); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); var webSocketOptions = new WebSocketOptions() { KeepAliveInterval = TimeSpan.FromSeconds(120), ReceiveBufferSize = 4 * 1024 }; app.UseWebSockets(webSocketOptions); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); app.Use(async(context, next) => { if (context.Request.Path == "/ws") { if (context.WebSockets.IsWebSocketRequest) { WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(); await NumbersResponder(context, webSocket); } else { context.Response.StatusCode = 400; } } else { await next(); } }); }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { var webSocketOptions = new WebSocketOptions() { KeepAliveInterval = TimeSpan.FromSeconds(120), ReceiveBufferSize = 4 * 1024 }; app.UseWebSockets(webSocketOptions); app.Use(async(context, next) => { if (context.WebSockets.IsWebSocketRequest) { var webSocket = await context.WebSockets.AcceptWebSocketAsync(); await Task.Run(async() => { for (;;) { await Task.Delay(1000); var items = Enumerable.Range(0, 12); foreach (var item in items) { var model = modelNames.OrderBy(x => Guid.NewGuid()).FirstOrDefault(); var rnd = new Random(); var usage = rnd.Next(50); var ram = rnd.Next(500); var data = new { title = model, usage, ram }; await SendMessageAsync(webSocket, JsonSerializer.Serialize(data)); } } }); } else { context.Response.StatusCode = 400; } }); }
public void Configure(IApplicationBuilder app) { app.UseSharedServices(); var webSocketOptions = new WebSocketOptions() { KeepAliveInterval = TimeSpan.FromSeconds(10), ReceiveBufferSize = 4 * 1024 }; app.UseWebSockets(webSocketOptions); app.UseMiddleware <WebsocketMiddleware>(); var refresher = app.ApplicationServices.GetService <AppleJWTKeyRefresher>(); refresher.Start(); var refresher2 = app.ApplicationServices.GetService <GoogleJWTKeyRefresher>(); refresher2.Start(); }
/// <summary> /// Inject dependent third-party components /// </summary> /// <param name="builder"></param> protected override void RegisterBuilder(ContainerBuilderWrapper builder) { var options = new WebSocketOptions(); var section = AppConfig.GetSection("WebSocket"); if (section.Exists()) { options = section.Get <WebSocketOptions>(); } base.RegisterBuilder(builder); builder.RegisterType(typeof(DefaultWSServiceEntryProvider)).As(typeof(IWSServiceEntryProvider)).SingleInstance(); if (AppConfig.ServerOptions.Protocol == CommunicationProtocol.WS) { RegisterDefaultProtocol(builder, options); } else if (AppConfig.ServerOptions.Protocol == CommunicationProtocol.None) { RegisterWSProtocol(builder, options); } }
public WebSocketMiddleware(RequestDelegate next, IOptions <WebSocketOptions> options, ILoggerFactory loggerFactory) { if (next == null) { throw new ArgumentNullException(nameof(next)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } _next = next; _options = options.Value; _allowedOrigins = _options.AllowedOrigins.Select(o => o.ToLowerInvariant()).ToList(); _anyOriginAllowed = _options.AllowedOrigins.Count == 0 || _options.AllowedOrigins.Contains("*", StringComparer.Ordinal); _logger = loggerFactory.CreateLogger <WebSocketMiddleware>(); // TODO: validate options. }
/// <summary> /// Hook up the Markdown Page Processing functionality in the Startup.Configure method /// </summary> /// <param name="builder"></param> /// <returns></returns> public static IApplicationBuilder UseLiveReload(this IApplicationBuilder builder) { var config = LiveReloadConfiguration.Current; if (config.LiveReloadEnabled) { var webSocketOptions = new WebSocketOptions() { KeepAliveInterval = TimeSpan.FromSeconds(240), ReceiveBufferSize = 256 }; builder.UseWebSockets(webSocketOptions); builder.UseMiddleware <LiveReloadMiddleware>(); LiveReloadFileWatcher.StartFileWatcher(); } return(builder); }
// This method gets called by the runtime. public void Configure(IApplicationBuilder app)//, ILoggerFactory loggerFactory) { app.UseElmCapture(); app.UseConvey(); app.UseMetricsActiveRequestMiddleware(); app.UseMetricsRequestTrackingMiddleware(); var webSocketOptions = new WebSocketOptions() { KeepAliveInterval = TimeSpan.FromSeconds(120), ReceiveBufferSize = 4 * 1024 }; app.UseWebSockets(webSocketOptions); app.UseRouting(); app.UseMetricServer(); app.UseHttpMetrics(); //app.UsePingEndpoint(); app.UseJaeger(); app.StartSocketConnections(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider) { loggerFactory.AddSerilog(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } var webSocketOptions = new WebSocketOptions() { KeepAliveInterval = TimeSpan.FromSeconds(120), ReceiveBufferSize = 4 * 1024 }; app.UseWebSockets(webSocketOptions); app.UseAppHub(); app.UseMvcWithDefaultRoute(); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { //loggerFactory.AddConsole(Microsoft.Extensions.Logging.LogLevel.Trace); var webSocketOptions = new WebSocketOptions() { KeepAliveInterval = TimeSpan.FromSeconds(60), ReceiveBufferSize = 8 * 1024 }; app.UseWebSockets(webSocketOptions); app.Run((context) => { var promise = new TaskCompletionSource <bool>(); theSyncContext !.Post(_ => { Task task = theCore !.HandleClientRequest(context); task.ContinueWith(completedTask => promise.CompleteFromTask(completedTask)); }, null); return(promise.Task); }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseCors("CorsPolicy"); app.UseSession(); app.UseMvc(); var webSocketOptions = new WebSocketOptions() { KeepAliveInterval = TimeSpan.FromSeconds(120), ReceiveBufferSize = 4 * 1024 }; app.UseWebSockets(webSocketOptions); app.Use(async(context, next) => { if (context.Request.Path == "/ws") { if (context.WebSockets.IsWebSocketRequest) { WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(); await Echo(context, webSocket); } else { context.Response.StatusCode = 400; } } else { await next(); } }); app.MapWebSocketManager("/move", serviceProvider.GetService <GameHandler>()); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(LogLevel.Debug); //loggerFactory.AddDebug(LogLevel.Debug); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseWebSockets(); var webSocketOptions = new WebSocketOptions() { KeepAliveInterval = TimeSpan.FromSeconds(120), ReceiveBufferSize = 4 * 1024 }; app.UseWebSockets(webSocketOptions); app.Use( async(context, next) => { if (context.Request.Path == "/ws") { if (context.WebSockets.IsWebSocketRequest) { WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(); await Echo(context, webSocket); } else { context.Response.StatusCode = 400; } } else { await next(); } }); app.UseFileServer(); }
public static void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseCors(); app.UseRouting(); app.UseHttpsRedirection(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); var webSocketOptions = new WebSocketOptions { KeepAliveInterval = TimeSpan.FromSeconds(120), ReceiveBufferSize = 4 * 1024 }; app.UseWebSockets(); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Test API V1"); }); }
public async Task ServerGracefullyClosesWhenApplicationEndsThenClientSendsCloseFrame() { using (StartLog(out var loggerFactory)) { var transportToApplication = Channel.CreateUnbounded <byte[]>(); var applicationToTransport = Channel.CreateUnbounded <byte[]>(); using (var transportSide = ChannelConnection.Create <byte[]>(applicationToTransport, transportToApplication)) using (var applicationSide = ChannelConnection.Create <byte[]>(transportToApplication, applicationToTransport)) using (var feature = new TestWebSocketConnectionFeature()) { var options = new WebSocketOptions { // We want to verify behavior without timeout affecting it CloseTimeout = TimeSpan.FromSeconds(20) }; var connectionContext = new DefaultConnectionContext(string.Empty, null, null); var ws = new WebSocketsTransport(options, transportSide, connectionContext, loggerFactory); var serverSocket = await feature.AcceptAsync(); // Give the server socket to the transport and run it var transport = ws.ProcessSocketAsync(serverSocket); // Run the client socket var client = feature.Client.ExecuteAndCaptureFramesAsync(); // close the client to server channel applicationToTransport.Writer.TryComplete(); _ = await client.OrTimeout(); await feature.Client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None).OrTimeout(); await transport.OrTimeout(); Assert.Equal(WebSocketCloseStatus.NormalClosure, serverSocket.CloseStatus); } } }