public static void Main(string[] args) { Console.WriteLine("BEGIN Main()"); // initialize variables int SleeptimeWhileStarting = 0; int SleeptimeWhileClosing = 0; string tempstring = Environment.GetEnvironmentVariable("ASPNETCORE_TOKEN"); if (!string.IsNullOrEmpty(tempstring)) { InprocessMode = false; tempstring = null; } else { InprocessMode = true; } tempstring = Environment.GetEnvironmentVariable("ANCMTestStartUpDelay"); if (!string.IsNullOrEmpty(tempstring)) { SleeptimeWhileStarting = Convert.ToInt32(tempstring); Startup.SleeptimeWhileStarting = SleeptimeWhileStarting; Console.WriteLine("SleeptimeWhileStarting: " + Startup.SleeptimeWhileStarting); tempstring = null; } tempstring = Environment.GetEnvironmentVariable("ANCMTestShutdownDelay"); if (!string.IsNullOrEmpty(tempstring)) { SleeptimeWhileClosing = Convert.ToInt32(tempstring); Startup.SleeptimeWhileClosing = SleeptimeWhileClosing; Console.WriteLine("SleeptimeWhileClosing: " + Startup.SleeptimeWhileClosing); } // Build WebHost IWebHost host = null; IWebHostBuilder builder = null; string startUpClassString = Environment.GetEnvironmentVariable("ANCMTestStartupClassName"); if (!string.IsNullOrEmpty(startUpClassString)) { Console.WriteLine("ANCMTestStartupClassName: " + startUpClassString); IConfiguration config = new ConfigurationBuilder() .AddCommandLine(args) .Build(); if (startUpClassString == "StartupHTTPS") { // load .\testresources\testcert.pfx string pfxPassword = "******"; if (File.Exists(@".\TestResources\testcert.pfx")) { _x509Certificate2 = new X509Certificate2(@".\TestResources\testcert.pfx", pfxPassword); } else { throw new Exception(@"Certificate file not found: .\TestResources\testcert.pfx of which password should " + pfxPassword); } } else if (startUpClassString == "StartupCompressionCaching" || startUpClassString == "StartupNoCompressionCaching") { if (startUpClassString == "StartupNoCompressionCaching") { StartupCompressionCaching.CompressionMode = false; } host = WebHost.CreateDefaultBuilder(args) .UseConfiguration(config) // BUGBUG below line is commented out because it causes 404 error with inprocess mode //.UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup <StartupCompressionCaching>() .Build(); } else if (startUpClassString == "StartupHelloWorld") { host = WebHost.CreateDefaultBuilder(args) .UseConfiguration(config) .UseStartup <StartupHelloWorld>() .Build(); } else if (startUpClassString == "StartupNtlmAuthentication") { host = WebHost.CreateDefaultBuilder(args) .UseConfiguration(config) .UseStartup <StartupNtlmAuthentication>() .Build(); } else if (startUpClassString == "StartupWithShutdownDisabled") { builder = new WebHostBuilder() .UseKestrel() .ConfigureServices(services => { const string PairingToken = "TOKEN"; string paringToken = null; if (InprocessMode) { Console.WriteLine("Don't use IISMiddleware for inprocess mode"); paringToken = null; } else { Console.WriteLine("Use IISMiddleware for outofprocess mode"); paringToken = builder.GetSetting(PairingToken) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{PairingToken}"); } services.AddSingleton <IStartupFilter>( new IISSetupFilter(paringToken) ); }) .UseConfiguration(config) .UseStartup <Startup>(); host = builder.Build(); } else { throw new Exception("Invalid startup class name : " + startUpClassString); } } if (host == null) { host = WebHost.CreateDefaultBuilder(args) .UseStartup <Startup>() .Build(); } // Initialize AppLifeTime events handler AppLifetime = (IApplicationLifetime)host.Services.GetService(typeof(IApplicationLifetime)); AppLifetime.ApplicationStarted.Register( () => { Thread.Sleep(1000); Console.WriteLine("AppLifetime.ApplicationStarted.Register()"); } ); AppLifetime.ApplicationStopping.Register( () => { Console.WriteLine("Begin: WebSocketConnections"); WebSocketConnections.CloseAll(); Console.WriteLine("End: WebSocketConnections"); Console.WriteLine("Begin: AppLifetime.ApplicationStopping.Register(), sleeping " + Startup.SleeptimeWhileClosing / 2); Thread.Sleep(Startup.SleeptimeWhileClosing / 2); Startup.SleeptimeWhileClosing = Startup.SleeptimeWhileClosing / 2; Console.WriteLine("End: AppLifetime.ApplicationStopping.Register()"); } ); AppLifetime.ApplicationStopped.Register( () => { Console.WriteLine("Begin: AppLifetime.ApplicationStopped.Register(), sleeping " + Startup.SleeptimeWhileClosing); Thread.Sleep(Startup.SleeptimeWhileClosing); Startup.SleeptimeWhileClosing = 0; Console.WriteLine("End: AppLifetime.ApplicationStopped.Register()"); } ); // run try { Console.WriteLine("BEGIN Main::Run()"); host.Run(); Console.WriteLine("END Main::Run()"); } catch (Exception ex) { Console.WriteLine("Exception error!!! " + ex.Message); } // Sleep before finishing if (Startup.SleeptimeWhileClosing > 0) { Console.WriteLine("Begin: SleeptimeWhileClosing " + Startup.SleeptimeWhileClosing); Thread.Sleep(Startup.SleeptimeWhileClosing); Console.WriteLine("End: SleeptimeWhileClosing"); } Console.WriteLine("END Main()"); }
private async Task Echo(WebSocket webSocket) { // add WebSocket connection to global WebSockets dictionary object so that we can use in graceful shutdown time int webSocketIndex = WebSocketConnections.Add(webSocket); var buffer = new byte[1024 * 4]; var result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None); bool closeFromServer = false; string closeFromServerCmd = WebSocketConnections.CloseFromServerCmd; string closingFromServer = WebSocketConnections.ClosingFromServer; int closeFromServerLength = closeFromServerCmd.Length; bool echoBack = true; int repeatCount = 1; while (!result.CloseStatus.HasValue) { if ((result.Count == closeFromServerLength && System.Text.Encoding.ASCII.GetString(buffer).Substring(0, result.Count) == closeFromServerCmd)) { // start closing handshake from backend process when client send "CloseFromServer" text message closeFromServer = true; await webSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, closingFromServer, CancellationToken.None); } else { if (buffer[0] == '_') { string tempString = System.Text.Encoding.ASCII.GetString(buffer).Substring(0, result.Count).ToLower(); switch (tempString) { case "_off": echoBack = false; break; case "_on": echoBack = true; break; case "_1": repeatCount = 1; break; case "_10": repeatCount = 10; break; case "_1000": repeatCount = 1000; break; default: break; } } if (echoBack) { for (int i = 0; i < repeatCount; i++) { await webSocket.SendAsync(new ArraySegment <byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None); } } } result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None); } // clean up WebSocket connection WebSocketConnections.Remove(webSocketIndex); if (closeFromServer) { webSocket.Dispose(); return; } await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None); webSocket.Dispose(); }