public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } ITextWebSocketSubprotocol textWebSocketSubprotocol = new PlainTextWebSocketSubprotocol(); app.UseStaticFiles() .UseWebSockets() .MapWebSocketConnections("/socket", new WebSocketConnectionsOptions { SupportedSubProtocols = new List <ITextWebSocketSubprotocol> { new JsonWebSocketSubprotocol(), textWebSocketSubprotocol }, DefaultSubProtocol = textWebSocketSubprotocol }) .Run(async(context) => { await context.Response.WriteAsync("-- Demo.AspNetCore.WebSocket --"); }); // Only for demo purposes, don't do this kind of thing to your production IWebSocketConnectionsService webSocketConnectionsService = serviceProvider.GetService <IWebSocketConnectionsService>(); System.Threading.Thread webSocketHeartbeatThread = new System.Threading.Thread(new System.Threading.ThreadStart(() => { while (true) { webSocketConnectionsService.SendToAllAsync("Demo.AspNetCore.WebSockets Heartbeat", System.Threading.CancellationToken.None).Wait(); System.Threading.Thread.Sleep(5000); } })); webSocketHeartbeatThread.Start(); }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } DefaultFilesOptions defaultFilesOptions = new (); defaultFilesOptions.DefaultFileNames.Clear(); defaultFilesOptions.DefaultFileNames.Add("websocket-api.html"); ITextWebSocketSubprotocol textWebSocketSubprotocol = new PlainTextWebSocketSubprotocol(); WebSocketConnectionsOptions webSocketConnectionsOptions = new () { AllowedOrigins = new HashSet <string> { "http://localhost:63290" }, SupportedSubProtocols = new List <ITextWebSocketSubprotocol> { new JsonWebSocketSubprotocol(), textWebSocketSubprotocol }, DefaultSubProtocol = textWebSocketSubprotocol, SendSegmentSize = 4 * 1024 }; app.UseDefaultFiles(defaultFilesOptions) .UseStaticFiles() .UseWebSockets() .MapWebSocketConnections("/socket", webSocketConnectionsOptions) .Run(async(context) => { await context.Response.WriteAsync("-- Demo.AspNetCore.WebSocket --"); }); } }