private IEnumerator <float> Reconnect() { yield return(Timing.WaitForSeconds(5f)); Logger.Info($"Reconnecting to {plugin.Config.HostAddress}:{plugin.Config.HostPort}..."); NetworkListener.Connect(plugin.Config.HostAddress, plugin.Config.HostPort, defaultdata); }
private void HomeView_Loaded(object sender, RoutedEventArgs e) { MainWindow = (MainWindow)Window.GetWindow(this); MainViewModel = (MainViewModel)MainWindow.DataContext; MainWindow.Width = 1200; MainWindow.Height = 800; MainWindow.CenterWindowOnScreen(); Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(() => { Request request = new Request { Type = RequestResponseType.FindCurrentUser, SessionToken = MainModel.SessionToken }; NetworkListener.SendRequest(request); })); ModelChangedHandler handler = null; handler = (string fieldName, Object field) => { if (fieldName == "User") { User user = MainModel.User; ((HomeViewModel)DataContext).DisplayName = $"{user.FirstName} {user.LastName} ({user.Username})"; } MainModel.ModelChanged -= handler; }; MainModel.ModelChanged += handler; }
/// <summary> /// Initializes a new instance of the <see cref="App"/> class. This initializes the singleton app object and is /// the first line of authored code executed, and as such is the logical equivalent of <c>Main()</c>. /// </summary> public App() { this.InitializeComponent(); this.Suspending += this.OnSuspending; NetworkListener.StartListener(); Task.Run(DataAccess.DataAccess.InitializeDatabaseAsync).Wait(); }
public void network_Listener_Starts_Listening_And_Initializes_Appropriate_Socket() { //Arrange NetworkListener testNetworkListener; IPAddress ipAddress; Socket expectedSocket; IPEndPoint localEndPoint; //Act testNetworkListener = new NetworkListener(); //ipAddress = IPAddress.Parse("192.168.42.98"); ipAddress = IPAddress.Parse(NetworkListener.GetIPv4Address()); expectedSocket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); localEndPoint = new IPEndPoint(ipAddress, 11111); var worker = new Thread(_ => testNetworkListener.StartListening()); worker.Start(); expectedSocket.Connect(localEndPoint); worker.Join(); //Assert testNetworkListener.clientSocket.LocalEndPoint.Should().Be(expectedSocket.RemoteEndPoint); }
private void Login(object sender, RoutedEventArgs e) { Request request = new Request { Type = RequestResponseType.Login, User = new User { Username = usernameOrEmail.Text, Email = usernameOrEmail.Text, Password = password.Password } }; ModelChangedHandler handler = null; handler = (string fieldName, Object field) => { if (fieldName == "SessionToken") { MainViewModel.CurrentView = new HomeView(); } MainModel.ModelChanged -= handler; }; MainModel.ModelChanged += handler; NetworkListener.SendRequest(request); }
public void NameTest() { string expected = "Test Name"; // TODO: Initialize to an appropriate value NetworkListener target = new NetworkListener(expected); // TODO: Initialize to an appropriate value string actual; actual = target.Name; Assert.AreEqual(expected, actual); }
public void AddReaderTest() { TagPassing target = new TagPassing("Tag Passing"); testPassing = target; NetworkListener rfidReader = new NetworkListener("TestListener"); target.AddPublisher(rfidReader); tagArgs = new TagReadEventArgs(); //rfidReader.TestReceivePacket(tagArgs); }
public void NetworkListenerNotConnectedTest() { User user = new User(); user.IPAddress = "0.0.0.0"; user.Port = 3000; NetworkListener networkListener = new NetworkListener(user); Assert.Equal(false, networkListener.IsConnected); }
public async Task Start() { ConnectionManager manager = new ConnectionManager(); NetworkListener listener = new NetworkListener( manager, IPAddress, Port ); await listener.Start(); }
public void Start() { Stop(); foreach (var item in NetworkHelper.GetIpv4s()) { NetworkListener listener = new NetworkListener(item); listener.OnInternetDataReceived += HandleInternetData; listener.Start(); current.Add(item, listener); } }
static void Main(string[] args) { //NetworkSimulator network; NetworkListener listener = new NetworkListener("Race Host"); //TagPassing passDetector = new TagPassing(); //passDetector.AddReader(listener); LoggerConsole log = new LoggerConsole(); LoggerSummary countLogger = new LoggerSummary(); LoggerBinary binaryLog = new LoggerBinary("tagReadings.bin"); //LoggerText textLog = new LoggerText("tagReadings.txt"); //LoggerXML log = new LoggerXML("test.xml"); //log.AddReader(listener); int initialiCapacity = 10000; PriorityCollectionBlocking<TagInfo> queue = new PriorityCollectionBlocking<TagInfo>("Queue", initialiCapacity); BufferReadings buffer = new BufferReadings(queue); ProcessBufferedReadings passDetector = new ProcessBufferedReadings("Pass Detector", queue); binaryLog.AddPublisher(listener); buffer.AddPublisher(listener); countLogger.AddPublisher(listener); log.AddPublisher(passDetector); passDetector.Start(); listener.Start(); //System.Windows.Forms.OpenFileDialog fileDialog = new System.Windows.Forms.OpenFileDialog(); //if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) //{ // string filename = fileDialog.FileName; // if (System.IO.File.Exists(filename)) // { // network = new NetworkSimulator(filename, new TestTagProcessor()); // network.AddListener(listener); // network.Start(true); // //log.Serialize(); // } // else // { // Console.WriteLine("Error! The specified file does not exist. Rerun the applications."); // } //} Console.WriteLine("Press any key stop the reading ..."); Console.Read(); listener.End(); passDetector.Exit(); countLogger.PrintStatsToConsole(); binaryLog.Dispose(); Console.WriteLine("Press any key to exit the demo ..."); Console.Read(); Environment.Exit(0); }
private IEnumerator <float> RefreshPolls() { while (true) { yield return(Timing.WaitForOneFrame); if (NetworkListener != null) { if (NetworkListener.IsRunning) { NetworkListener.PollEvents(); } } } }
private async Task RefreshPolls() { while (true) { await Task.Delay(15); if (NetworkListener != null) { if (NetworkListener.IsRunning) { NetworkListener.PollEvents(); } } } }
private void Logout(object sender, RoutedEventArgs e) { Request request = new Request { Type = RequestResponseType.Logout, SessionToken = MainModel.SessionToken }; MainModel.User = null; MainModel.SessionToken = null; NetworkListener.SendRequest(request); MainViewModel.CurrentView = new LoginView(); }
public ServiceContainer(int port, Dictionary <Type, object> services, Dictionary <Type, ISerializer> serializers, Dictionary <string, DelegateContract> streamingContracts) { _services = services; _streamingContracts = streamingContracts; var networkAdapterServices = streamingContracts .Select(pair => new NetworkAdapterService(pair.Key, pair.Value)).ToList(); _networkAdapters = networkAdapterServices .ToDictionary(service => service.StreamingType); _networkListener = new NetworkListener(this, this); var interfaceInfoProvider = new InterfaceInfoProvider(services.Keys.ToList()); _messageBuilder = new ServiceMessageBuilder(interfaceInfoProvider, new DefaultSerializer(), serializers, networkAdapterServices); Init(port); }
/// <summary> /// Handles the read channel messages. /// </summary> /// <param name="context"></param> /// <param name="message"></param> public override void ChannelRead(IChannelHandlerContext context, object message) { try { NetworkListener listener = Preconditions.Check.NotNull(context.Channel.GetAttribute(CURR_LISTENER).Get(), "Network attribute key is null."); if (listener != null && context.Channel.Registered) { listener.MessageRead(context, message); } } finally { ReferenceCountUtil.Release(message); } }
public void test_Raising_Of_Event_OnNewConnection() { //Arrange NetworkClient networkClient; NetworkListener networkListener; IPHostEntry host; Socket actualSocket; Socket eventSocket = null; string ipaddress = null; string address = null; //var testNewConnection; //Act host = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { ipaddress = ip.ToString(); } } address = ipaddress + ":" + "11111"; networkListener = new NetworkListener(); networkListener.NewConnection += TestNewConnection; void TestNewConnection(object sender, NewConnectionHandlerArgs e) { System.Console.WriteLine("Event Fired!"); } networkClient = new NetworkClient(); var worker = new Thread(_ => networkListener.StartListening()); worker.Start(); actualSocket = networkClient.Connect(address); worker.Join(); //Assert //eventSocket.RemoteEndPoint.Should().Be(networkListener.clientSocket.LocalEndPoint); Assert.True(true); }
void Awake() { networkListener = new NetworkListener(); commands = new Commands(); Commands.onFullState += command => { bool initialLoad = gameState == null; if (initialLoad) { gameState = new GameState(); } gameState.worldWidth = command.worldWidth; gameState.worldHeight = command.worldHeight; bool setHexByPosition = Utils.ListToDictionary(command.hexByPositionKeys, command.hexByPositionValues, ref gameState.hexByPosition); bool setHexPositionsByNationName = Utils.ListToDictionaryList(command.hexPositionsByNationNameKeys, command.hexPositionsByNationNameValues, ref gameState.hexPositionsByNationName); if (setHexByPosition && setHexPositionsByNationName) { Debug.Log("[GAME MANAGER] State update successful"); } else { Debug.LogError("[GAME MANAGER] State update failed!"); } if (initialLoad) { onRebuildWorld?.Invoke(); } }; Commands.onInvalidPlayerInfo += command => { Debug.LogWarning($"[GAME MANAGER] Invalid player info sent to server as {command.error}"); }; Commands.onUnknown += command => { Debug.LogWarning($"[GAME MANAGER] Unknown Server Command of type {command.type} and json {command.json}"); }; }
public void network_Client_Successfully_Connects_To_Endpoint() { //Arrange NetworkClient networkClient; NetworkListener networkListener; IPHostEntry host; Socket actualSocket; string ipaddress = null; string address = null; //Act host = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { ipaddress = ip.ToString(); } } //ipaddress = NetworkListener.GetIPv4Address(); address = ipaddress + ":" + "11111"; networkListener = new NetworkListener(); var worker = new Thread(_ => networkListener.StartListening()); worker.Start(); networkClient = new NetworkClient(); actualSocket = networkClient.Connect(address); worker.Join(); if (worker.IsAlive) { Thread.Sleep(1000); } //Assert networkClient._ipaddress.Should().Be(ipaddress); networkClient._portNumber.Should().Be(11111); actualSocket.RemoteEndPoint.Should().Be(networkListener.clientSocket.LocalEndPoint); }
/// <summary> /// Start the STS /// </summary> /// <param name="args">no command line arguments are used at this moment</param> static void Main(string[] args) { try { // start the socket acceptor NetworkListener nl = new NetworkListener(); // Get base address from app settings in configuration Uri baseAddress = new Uri(ConfigurationManager.AppSettings["baseAddress"]); Uri baseMexAddress = new Uri(ConfigurationManager.AppSettings["baseMexAddress"]); List <ServiceHost> hostList = new List <ServiceHost>(); try { // // Start the STSs // //hostList.Add(StartSTS(typeof(CertificateAuthSTS), "smartcard", baseAddress, baseMexAddress)); hostList.Add(StartSTS(typeof(SelfIssuedSamlAuthSTS), "selfissuedsaml", baseAddress, baseMexAddress)); //hostList.Add(StartSTS(typeof(UserNameAuthSTS), "usernamepassword", baseAddress, baseMexAddress)); Console.Write("\n\nPress <ENTER> to terminate services\n\n"); Console.ReadLine(); } finally { foreach (ServiceHost host in hostList) { host.Close(); } } } catch (Exception e) { Console.WriteLine("An unexpected fault was encountered:\n{0}", e.ToString()); } }
private static void Main(string[] args) { // initializing logger Logger.Initialize(); // scripts compiler initialization SmartCompiler.Initialize("Scripts", "Assemblies.txt"); SmartCompiler.Compile(null, ScriptFileType.CS, true, null); #if INSTALL_DB_ON_STARTUP InstallDataBase(); #endif // initializing data provider DataProvider.Initialize ( Settings.Default.SqlEngine, Settings.Default.SqlServerConnectionString, Settings.Default.SqlServerConnectionsPoolSize, Settings.Default.SqlServerDumpInterval ); // initializing network listener NetworkListener.Initialize ( new IPEndPoint ( IPAddress.Parse(Settings.Default.CacheServiceListenerAddress), Settings.Default.CacheServiceListenerPort ), Settings.Default.CacheServiceEnableFirewall ); while (Console.ReadKey(true) != null) { } }
/// <summary> /// Start the STS /// </summary> /// <param name="args">no command line arguments are used at this moment</param> static void Main(string[] args) { try { // start the socket acceptor NetworkListener nl = new NetworkListener(); // Get base address from app settings in configuration Uri baseAddress = new Uri(ConfigurationManager.AppSettings["baseAddress"]); Uri baseMexAddress = new Uri(ConfigurationManager.AppSettings["baseMexAddress"]); List<ServiceHost> hostList = new List<ServiceHost>(); try { // // Start the STSs // //hostList.Add(StartSTS(typeof(CertificateAuthSTS), "smartcard", baseAddress, baseMexAddress)); hostList.Add(StartSTS(typeof(SelfIssuedSamlAuthSTS), "selfissuedsaml", baseAddress, baseMexAddress)); //hostList.Add(StartSTS(typeof(UserNameAuthSTS), "usernamepassword", baseAddress, baseMexAddress)); Console.Write("\n\nPress <ENTER> to terminate services\n\n"); Console.ReadLine(); } finally { foreach (ServiceHost host in hostList) { host.Close(); } } } catch (Exception e) { Console.WriteLine("An unexpected fault was encountered:\n{0}", e.ToString()); } }
public ChatApplication(User user) { _network = new Network(); _conversation = new Conversation(); _networkListener = new NetworkListener(user, _network, _conversation); }
public Connection(NetworkListener networkListener) { this.networkListener = networkListener; _Serializer = new PacketSerializer(); }
public void SetListener(NetworkListener listener) { this.listener = listener; }
public ServerManager() { _listener = new NetworkListener(); }
private List<PlayerIndex> pis; // connected controllers. #endregion Fields #region Constructors // call base class ctor /// <summary> /// Constructor /// </summary> public Controller( Game g ) : base(g) { // save reference to the main game itself game = this.Game as SPW; netConn = new NetworkListener(); //find number of controllers attached. int nConn = 0; Array players = Enum.GetValues( typeof( PlayerIndex ) ); pis = new List<PlayerIndex>(); gpPrevStates = new Dictionary<PlayerIndex, GamePadState>(); gpCurrStates = new Dictionary<PlayerIndex, GamePadState>(); // Prepare to track states // for player controllers // that are connected. foreach( PlayerIndex pi in players ) { if( GamePad.GetState( pi ).IsConnected ) { nConn++; pis.Add( pi ); gpPrevStates.Add( pi, new GamePadState() ); gpCurrStates.Add( pi, new GamePadState() ); } } }
private void StartRaceThread() { listener = new NetworkListener("Race Host"); int initialiCapacity = 10000; PriorityCollectionBlocking<TagInfo> queue = new PriorityCollectionBlocking<TagInfo>("Queue", initialiCapacity); BufferReadings buffer = new BufferReadings(queue); passDetector = new ProcessBufferedReadings("Pass Detector", queue); readingsLogger.AddPublisher(listener); buffer.AddPublisher(listener); passingsLogger.AddPublisher(passDetector); passDetector.Start(); listener.Start(); }
/// <summary> /// Create a new local vote listener from a list of peers /// </summary> /// <param name="timeout">The timeout for use in the event system</param> /// <param name="networkListener">A networklistener to register created objects in</param> /// <param name="peers">A collection of connected peers. Will be updated if a peer is found to be dead</param> public LocalVoteListener(int timeout, NetworkListener networkListener, IEnumerable <IPAddress> peers) : base(timeout) { this.networkListener = networkListener; Peers = peers.ToDictionary(ip => ip, ip => PeerState.Alive); }
public void listen(NetworkListener listener) { this.listener = listener; }
private void StartRaceThread() { listener = new NetworkListener("Race Host"); int initialiCapacity = 10000; PriorityCollectionBlocking<TagInfo> queue = new PriorityCollectionBlocking<TagInfo>("Queue", initialiCapacity); // The queue above is used to communicate between the buffer below and the passDetector. BufferReadings buffer = new BufferReadings(queue); passDetector = new ProcessBufferedReadings("Pass Detector", queue); buffer.AddPublisher(listener); // Subscribe the loggers to the publishers. readingsLogger.AddPublisher(listener); binaryLogger.AddPublisher(listener); passingsLogger.AddPublisher(passDetector); // Start the pass detection in its own thread. passDetector.Start(); // Start the networkListener. listener.Start(); }
public static async Task StartAsync() { using (await _queue.GetBlockingScope()) { if (_initialized) { throw new InvalidOperationException("Bootstrapper has already been invoked"); } var constantSettings = ApplicationBootstrapper.ConstantSettingsProvider.Find(); var directoryPath = AppDomain.CurrentDomain.BaseDirectory; await WriteDatabaseInitializer.Initialize(new WriteDatabaseConfiguration(directoryPath, constantSettings.DatabaseFilePath, constantSettings.DatabaseEncryptionKey)); await ReadDatabaseInitializer.Initialize(); var applicationSettings = await new ApplicationSettingsRepository(WriteDatabaseInitializer.DatabaseContext).LoadAsync(); var applicationListenerUri = string.Format(constantSettings.ApplicationListenerUri, constantSettings.SystemIpAddress, applicationSettings.ApplicationCommunicationPort); var builder = new ContainerBuilder(); var assemblies = new[] { Assembly.GetEntryAssembly() } .Union(new[] { "iGP11.Library.dll", "iGP11.Library.Component.dll", "iGP11.Library.Component.DataAnnotations.dll", "iGP11.Library.DDD.dll", "iGP11.Library.EventPublisher.dll", "iGP11.Library.File.dll", "iGP11.Library.Hub.dll", "iGP11.Library.Hub.Client.dll", "iGP11.Library.Hub.Shared.dll", "iGP11.Library.Hub.Transport.dll", "iGP11.Library.Network.dll", "iGP11.Library.Scheduler.dll", "iGP11.Tool.Application.dll", "iGP11.Tool.Application.Api.dll", "iGP11.Tool.Domain.dll", "iGP11.Tool.Infrastructure.Communication.dll", "iGP11.Tool.Infrastructure.External.dll", "iGP11.Tool.Infrastructure.Database.dll", "iGP11.Tool.Localization.dll", "iGP11.Tool.ReadModel.dll", "iGP11.Tool.ReadModel.Api.dll", "iGP11.Tool.Shared.dll" } .Select(Assembly.LoadFrom)) .ToArray(); foreach (var assembly in assemblies) { builder.RegisterAssemblyTypes(assembly) .AsSelf() .AsImplementedInterfaces(); } builder.Register( context => { var listener = new NetworkListener($"{applicationListenerUri}/", context.Resolve <ILogger>()); foreach (dynamic handler in assemblies.GetImplementations(typeof(INetworkCommandHandler)).Select(context.Resolve)) { listener.Register(handler); } return(listener); }) .SingleInstance() .AsSelf() .AsImplementedInterfaces(); var proxyCommunicationPort = applicationSettings.ProxyCommunicationPort; var systemIpAddress = constantSettings.SystemIpAddress; var eventPublisher = new EventPublisher(); _scheduler = new BlockingScheduler(eventPublisher.Collect, Interval); _scheduler.Start(); builder.Register(context => Logger.Current).SingleInstance().AsSelf().AsImplementedInterfaces(); builder.Register(context => WriteDatabaseInitializer.DatabaseContext).SingleInstance().AsSelf().AsImplementedInterfaces(); builder.Register(context => ReadDatabaseInitializer.Database).SingleInstance().AsSelf().AsImplementedInterfaces(); builder.Register(context => new CommunicatorFactory(systemIpAddress, proxyCommunicationPort, Logger.Current)).AsSelf().AsImplementedInterfaces(); builder.Register(context => eventPublisher).SingleInstance().AsSelf().AsImplementedInterfaces(); builder.Register(context => constantSettings.Plugins).AsSelf().AsImplementedInterfaces(); builder.Register(context => new NetworkPublisher(applicationListenerUri)).AsSelf().AsImplementedInterfaces(); builder.Register(context => new GameSettingsProcessWatcher( constantSettings.Plugins, systemIpAddress, proxyCommunicationPort, context.Resolve <ComponentAssembler>(), context.Resolve <IDirectoryRepository>(), context.Resolve <IGameRepository>(), context.Resolve <IInjectionService>(), Logger.Current, context.Resolve <IProcessWatcher>())) .SingleInstance() .AsSelf() .AsImplementedInterfaces(); var hubEventRepository = new InMemoryEventRepository <HubEvent>(); var endpointEventRepository = new InMemoryEventRepository <EndpointEvent>(); var transport = new InMemoryTransport(); var eventSerializerFactory = new DataContractEventSerializerFactory(); var hubClientFactory = new HubClientFactory(transport, eventSerializerFactory); _hub = new Hub(hubEventRepository, endpointEventRepository, transport, Logger.Current); var commandEndpointId = EndpointId.Generate(); var queryEndpointId = EndpointId.Generate(); builder.Register(context => new DomainActionBuilder(new ActionBuilder(hubClientFactory, eventSerializerFactory), commandEndpointId)).AsSelf().AsImplementedInterfaces(); DependencyResolver.Current = new AutofacResolver(builder.Build()); var domainCommandHubHost = new DomainCommandHubHost(commandEndpointId, queryEndpointId, hubClientFactory); foreach (dynamic handler in assemblies.GetImplementations(typeof(IDomainCommandHandler <>)).Select(DependencyResolver.Current.Resolve)) { ListenFor(domainCommandHubHost, handler); } var domainEventHubHost = new DomainEventHubHost(queryEndpointId, hubClientFactory); foreach (dynamic handler in assemblies.GetImplementations(typeof(IDomainEventHandler <>)).Select(DependencyResolver.Current.Resolve)) { ListenFor(domainEventHubHost, handler); } domainCommandHubHost.Start(); domainEventHubHost.Start(); _initialized = true; } }
/// <summary> /// Initializes a new instance of the <see cref="App"/> class. This initializes the singleton app object and is /// the first line of authored code executed, and as such is the logical equivalent of <c>Main()</c>. /// </summary> public App() { this.InitializeComponent(); this.Suspending += this.OnSuspending; NetworkListener.StartListener(); }
public MatchListener(NetworkListener nl) { this.nl = nl; }
public void NetworkListenerConstructorTest() { string name = string.Empty; // TODO: Initialize to an appropriate value NetworkListener target = new NetworkListener(name); Assert.Inconclusive("TODO: Implement code to verify target"); }
public static void Main(string[] args) { Console.Title = $"{Name} - Build: {Version}"; var config = new LoggingConfiguration(); var developerLog = new ColoredConsoleTarget() { Name = "developer", Layout = @"[${date:format=HH\:mm\:ss}] [${level}] ${message} ${exception}" }; var developerFile = new FileTarget() { Name = "developer-file", FileName = "../../../logs/server/Build ${assembly-version}/${level}/${date:format=dd-MM-yyyy}.txt", Layout = @"[${date:format=HH\:mm\:ss}] [${level}] ${message} ${exception}" }; config.AddTarget(developerLog); config.AddTarget(developerFile); config.AddRule(LogLevel.Info, LogLevel.Fatal, developerFile); config.AddRuleForAllLevels(developerLog); LogManager.Configuration = config; RollbarLocator.RollbarInstance.Configure(new RollbarConfig(RollbarId)); Info("Game Server is loading..."); XmlLibrary.Init(); Database = new Database(); LoEUtils = new Util((message) => Warn(message)); try { Map.BinaryMapsCache = new Dictionary <string, KeyValuePair <bool, byte[]> >(); Map.LoadEmbeddedMaps(); var manager = new WorldManager(); var connection = new NetworkListener(manager); NetworkProccessor.Start(); connection.Listen(); manager.BeginUpdate(); Info("Game Server is loading... OK!"); while (Console.ReadKey(true).Key != ConsoleKey.Escape) { ; } Database.Dispose(); Info("Game Server has been stopped."); Environment.Exit(0); } catch (Exception e) { Database.Dispose(); Warn($"An error occurred! {e.ToString()}"); Error(e); Thread.Sleep(100); Warn("Press 'ESC' to close..."); while (Console.ReadKey(true).Key != ConsoleKey.Escape) { ; } Environment.Exit(-1); } }