コード例 #1
0
ファイル: ConsoleUtils.cs プロジェクト: tritao/BuildSharp
        public static void SetupExitHandler(ConsoleEventHandler handler)
        {
            if (!IsWindows)
                return;

            SetConsoleCtrlHandler(handler, add: true);
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: FominVlad/Packet-tracer
        static void Main(string[] args)
        {
            ColourPrinter.Print("<==== Create Simplified Driver ====>", ConsoleColor.Green);
            ColourPrinter.Print("-- Enter the package in the format: P[COMMAND_CHARACTER][:][PARAMETERS][:]E", ConsoleColor.Green);

            // Buffer for entered characters in the console.
            StringBuilder       stringBuilder = new StringBuilder();
            Packet              packet;
            CommandValidator    commandValidator    = new CommandValidator(new Regex(@"^P[A-Za-z]+:.+:E$"));
            ConsoleEventHandler consoleEventHandler = new ConsoleEventHandler(commandValidator);

            while (true)
            {
                try
                {
                    ConsoleKeyInfo keyPress = Console.ReadKey(true);
                    char           input    = keyPress.KeyChar;

                    // We allow you to enter only characters from the table ASCII (32 - 127).
                    if ((int)input >= 32 && (int)input <= 127)
                    {
                        Console.Write(input);

                        stringBuilder.Append(input);
                    }
                    // When you press "Enter" - clear the buffer and throw the code "NACK".
                    if ((int)input == 13)
                    {
                        stringBuilder.Clear();
                        ColourPrinter.Print("\nNACK", ConsoleColor.Red);
                    }

                    // Check the validity of the entered package and process it.
                    if (commandValidator.IsValid(stringBuilder.ToString()))
                    {
                        packet = commandValidator.GetPacketFromStr(stringBuilder.ToString());

                        consoleEventHandler.HandlePacket(packet);

                        // We clear the buffer after processing the packet.
                        stringBuilder.Clear();
                    }
                }
                catch (CommandException cmdEx)
                {
                    // In the future - some kind of action.
                }
                catch (Exception ex)
                {
                    // In case of an error, we throw the code "NACK".
                    ColourPrinter.Print("\nNACK", ConsoleColor.Red);
                    // We clear the console buffer.
                    stringBuilder.Clear();
                    // Display error message.
                    ColourPrinter.Print(ex.Message, ConsoleColor.White, ConsoleColor.Red);
                }
            }
        }
コード例 #3
0
        public static void SetupExitHandler(ConsoleEventHandler handler)
        {
            if (!IsWindows)
            {
                return;
            }

            SetConsoleCtrlHandler(handler, add: true);
        }
コード例 #4
0
ファイル: ConsoleUtility.cs プロジェクト: Kuzaki/alkahest
 public static void AddConsoleEventHandler(ConsoleEventHandler handler)
 {
     try
     {
         SetConsoleCtrlHandler(handler, true);
     }
     catch (DllNotFoundException)
     {
     }
 }
コード例 #5
0
ファイル: ConsoleUtility.cs プロジェクト: Kuzaki/alkahest
 public static void RemoveConsoleEventHandler(ConsoleEventHandler handler)
 {
     try
     {
         SetConsoleCtrlHandler(handler, false);
     }
     catch (DllNotFoundException)
     {
     }
 }
コード例 #6
0
ファイル: WaitFor.cs プロジェクト: peterson1/ErrH
		public Waiter(ConsoleControl.ConsoleControl cons)
		{
			this._cons = cons;
			this._rtb = cons.InternalRichTextBox;
			this._consHandlr = new ConsoleEventHandler(OnConsInput);
			this._rtbKeyPress = new KeyPressEventHandler(OnRtbKeyPress);
			//this._rtbKeyDown = new KeyEventHandler(OnRtbKeyDown);

			this._cons.OnConsoleInput += _consHandlr;
			this._cons.InternalRichTextBox.KeyPress += _rtbKeyPress;
			//this._cons.InternalRichTextBox.KeyDown += _rtbKeyDown;
		}
コード例 #7
0
ファイル: WaitFor.cs プロジェクト: orf53975/ErrH
            public Waiter(ConsoleControl.ConsoleControl cons)
            {
                this._cons        = cons;
                this._rtb         = cons.InternalRichTextBox;
                this._consHandlr  = new ConsoleEventHandler(OnConsInput);
                this._rtbKeyPress = new KeyPressEventHandler(OnRtbKeyPress);
                //this._rtbKeyDown = new KeyEventHandler(OnRtbKeyDown);

                this._cons.OnConsoleInput += _consHandlr;
                this._cons.InternalRichTextBox.KeyPress += _rtbKeyPress;
                //this._cons.InternalRichTextBox.KeyDown += _rtbKeyDown;
            }
コード例 #8
0
ファイル: Main.cs プロジェクト: zerodowned/Ulmeta
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            AppDomain.CurrentDomain.ProcessExit        += new EventHandler(CurrentDomain_ProcessExit);

            Console.BackgroundColor = ConsoleColor.Black;
            Console.ForegroundColor = ConsoleColor.Gray;

            Console.Title = "UO Aberration : Core";

            for (int i = 0; i < args.Length; ++i)
            {
                if (Insensitive.Equals(args[i], "-debug"))
                {
                    m_Debug = true;
                }
                else if (Insensitive.Equals(args[i], "-service"))
                {
                    m_Service = true;
                }
                else if (Insensitive.Equals(args[i], "-profile"))
                {
                    Profiling = true;
                }
                else if (Insensitive.Equals(args[i], "-nocache"))
                {
                    m_Cache = false;
                }
                else if (Insensitive.Equals(args[i], "-haltonwarning"))
                {
                    m_HaltOnWarning = true;
                }
            }

            try
            {
                if (m_Service)
                {
                    if (!Directory.Exists("Logs"))
                    {
                        Directory.CreateDirectory("Logs");
                    }

                    Console.SetOut(m_MultiConOut = new MultiTextWriter(new FileLogger("Logs/Console.log")));
                }

                else
                {
                    Console.SetOut(m_MultiConOut = new MultiTextWriter(Console.Out));
                }
            }

            catch                   {                       }

            m_Thread   = Thread.CurrentThread;
            m_Process  = Process.GetCurrentProcess();
            m_Assembly = Assembly.GetEntryAssembly();

            if (m_Thread != null)
            {
                m_Thread.Name = "Core Thread";
            }

            if (BaseDirectory.Length > 0)
            {
                Directory.SetCurrentDirectory(BaseDirectory);
            }

            Timer.TimerThread ttObj = new Timer.TimerThread();
            timerThread      = new Thread(new ThreadStart(ttObj.TimerMain));
            timerThread.Name = "Timer Thread";

            Version ver = m_Assembly.GetName().Version;

            /*
             * ServUO's Original Code
             * if (File.Exists("publish.txt"))
             * {
             *  try
             *  {
             *      FileStream fs = new FileStream("publish.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
             *      StreamReader sr = new StreamReader(fs);
             *
             *      publishNumber = sr.ReadLine();
             *
             *      sr.Close();
             *      fs.Close();
             *  }
             *  catch
             *  { }
             * }*/
            //Concept Expanded based upon ServUO's publish number.

            string       header       = "";
            ConsoleColor desiredColor = ConsoleColor.White;

            if (File.Exists("header.txt"))
            {
                bool chopColor = false;

                try
                {
                    FileStream   file   = new FileStream("header.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
                    StreamReader reader = new StreamReader(file);

                    string determineTextColor = (string)(reader.ReadLine().Trim().ToLower());

                    if (Enum.TryParse <ConsoleColor>(determineTextColor, true, out desiredColor))
                    {
                        chopColor = true;
                    }

                    else
                    {
                        Utility.PushColor(ConsoleColor.White);
                    }

                    if (chopColor)
                    {
                        header = (string)(reader.ReadToEnd());
                    }

                    file.Close();
                    reader.Close();

                    file.Dispose();
                    reader.Dispose();
                }

                catch
                {
                    Utility.PushColor(ConsoleColor.Red);
                    Console.Write("Error: ");
                    Utility.PushColor(ConsoleColor.White);
                    Console.WriteLine("Your are either missing header.txt or it is misconfigured.");
                }
            }

            else
            {
                Utility.PushColor(ConsoleColor.Red);
                Console.Write("Error: ");
                Utility.PushColor(ConsoleColor.White);
                Console.WriteLine("header.txt could not be located.");
            }

            Utility.PushColor(desiredColor);
            Console.WriteLine(header);
            Utility.PushColor(ConsoleColor.White);
            Console.WriteLine();
            Console.WriteLine("Core ({3}): Running on .NET Framework Version {0}.{1}.{2}", Environment.Version.Major, Environment.Version.Minor, Environment.Version.Build, Environment.Is64BitProcess ? "x64" : "x86");

            string s = Arguments;

            if (s.Length > 0)
            {
                Console.WriteLine("Core: Running with arguments: {0}", s);
            }

            m_ProcessorCount = Environment.ProcessorCount;

            if (m_ProcessorCount > 1)
            {
                m_MultiProcessor = true;
            }

            if (m_MultiProcessor || Is64Bit)
            {
                Console.WriteLine("Core: Optimizing for {0} {2}processor{1}", m_ProcessorCount, m_ProcessorCount == 1 ? "" : "s", Is64Bit ? "64-bit " : "");
            }

            int platform = (int)Environment.OSVersion.Platform;

            if (platform == 4 || platform == 128)                // MS 4, MONO 128
            {
                m_Unix = true;
                Console.WriteLine("Core: Unix environment detected");
            }
            else
            {
                m_ConsoleEventHandler = new ConsoleEventHandler(OnConsoleEvent);
                SetConsoleCtrlHandler(m_ConsoleEventHandler, true);
            }

            if (GCSettings.IsServerGC)
            {
                Console.WriteLine("Core: Server garbage collection mode enabled");
            }

            while (!ScriptCompiler.Compile(m_Debug, m_Cache))
            {
                Console.WriteLine("Scripts: One or more scripts failed to compile or no script files were found.");

                if (m_Service)
                {
                    return;
                }

                Console.WriteLine(" - Press return to exit, or R to try again.");

                if (Console.ReadKey(true).Key != ConsoleKey.R)
                {
                    return;
                }
            }

            ScriptCompiler.Invoke("Configure");

            Region.Load();
            World.Load();

            ScriptCompiler.Invoke("Initialize");

            MessagePump messagePump = m_MessagePump = new MessagePump();

            timerThread.Start();

            for (int i = 0; i < Map.AllMaps.Count; ++i)
            {
                Map.AllMaps[i].Tiles.Force();
            }

            NetState.Initialize();

            EventSink.InvokeServerStarted();

            try
            {
                DateTime now, last = DateTime.UtcNow;

                const int   sampleInterval = 100;
                const float ticksPerSecond = (float)(TimeSpan.TicksPerSecond * sampleInterval);

                long sample = 0;

                while (m_Signal.WaitOne())
                {
                    Mobile.ProcessDeltaQueue();
                    Item.ProcessDeltaQueue();

                    Timer.Slice();
                    messagePump.Slice();

                    NetState.FlushAll();
                    NetState.ProcessDisposedQueue();

                    if (Slice != null)
                    {
                        Slice();
                    }

                    if ((++sample % sampleInterval) == 0)
                    {
                        now = DateTime.UtcNow;
                        m_CyclesPerSecond[m_CycleIndex++ % m_CyclesPerSecond.Length] =
                            ticksPerSecond / (now.Ticks - last.Ticks);
                        last = now;
                    }
                }
            }
            catch (Exception e)
            {
                CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, true));
            }
        }
コード例 #9
0
ファイル: Main.cs プロジェクト: zerodowned/angelisland
		public static void Main(string[] args)
		{
#if !DEBUG
			AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
#endif
			AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);

			for (int i = 0; i < args.Length; ++i)
			{
				if (Insensitive.Equals(args[i], "-debug"))
					m_Debug = true;
				else if (Insensitive.Equals(args[i], "-service"))
					m_Service = true;
				else if (Insensitive.Equals(args[i], "-profile"))
					Profiling = true;
				else if (Insensitive.Equals(args[i], "-nocache"))
					m_Cache = false;
				else if (Insensitive.Equals(args[i], "-haltonwarning"))
					m_HaltOnWarning = true;
				else if (Insensitive.Equals(args[i], "-vb"))
					m_VBdotNET = true;
			}

			try
			{
				if (m_Service)
				{
					if (!Directory.Exists("Logs"))
						Directory.CreateDirectory("Logs");

					Console.SetOut(m_MultiConOut = new MultiTextWriter(Console.Out, new FileLogger("Logs/Console.log")));
				}
				else
				{
					Console.SetOut(m_MultiConOut = new MultiTextWriter(Console.Out));
				}
			}
			catch (Exception ex) { EventSink.InvokeLogException(new LogExceptionEventArgs(ex)); }

			m_Thread = Thread.CurrentThread;
			m_Process = Process.GetCurrentProcess();
			m_Assembly = Assembly.GetEntryAssembly();

			if (m_Thread != null)
				m_Thread.Name = "Core Thread";

			if (BaseDirectory.Length > 0)
				Directory.SetCurrentDirectory(BaseDirectory);

			Timer.TimerThread ttObj = new Timer.TimerThread();
			timerThread = new Thread(new ThreadStart(ttObj.TimerMain));
			timerThread.Name = "Timer Thread";

			Version ver = m_Assembly.GetName().Version;

			// Added to help future code support on forums, as a 'check' people can ask for to it see if they recompiled core or not
			Console.WriteLine("Angel Island - [www.game-master.net] Version {0}.{1}.{3}, Build {2}", ver.Major, ver.Minor, ver.Revision, ver.Build);
#if DEBUG
            Console.WriteLine("[Debug Build Enabled]");
#endif
			string s = Arguments;

			if (s.Length > 0)
				Console.WriteLine("Core: Running with arguments: {0}", s);

			m_ProcessorCount = Environment.ProcessorCount;

			if (m_ProcessorCount > 1)
				m_MultiProcessor = true;

			if (m_MultiProcessor || Is64Bit)
				Console.WriteLine("Core: Optimizing for {0} {2}processor{1}", m_ProcessorCount, m_ProcessorCount == 1 ? "" : "s", Is64Bit ? "64-bit " : "");

			int platform = (int)Environment.OSVersion.Platform;
			if ((platform == 4) || (platform == 128))
			{ // MS 4, MONO 128
				m_Unix = true;
				Console.WriteLine("Core: Unix environment detected");
			}
			else
			{
				m_ConsoleEventHandler = new ConsoleEventHandler(OnConsoleEvent);
				SetConsoleCtrlHandler(m_ConsoleEventHandler, true);
			}

			while (!ScriptCompiler.Compile(m_Debug))
			{
				if (m_Quiet) //abort and exit if compile scripts failed
					return;

				Console.WriteLine("Scripts: One or more scripts failed to compile or no script files were found.");
				Console.WriteLine(" - Press return to exit, or R to try again.");

				string line = Console.ReadLine();
				if (line == null || line.ToLower() != "r")
					return;
			}

			// adam: I believe the new startup logic is nore robust as it attempts to prevents timers from firing 
			//  before the shard is fully up and alive.

			Region.Load();

			SocketPool.Create();

			MessagePump ms = m_MessagePump = new MessagePump();

			timerThread.Start();

			for (int i = 0; i < Map.AllMaps.Count; ++i)
				((Map)Map.AllMaps[i]).Tiles.Force();

			NetState.Initialize();

			EventSink.InvokeServerStarted();

#if !DEBUG
			try
			{
#endif
				while (m_Signal.WaitOne())
				{
					Mobile.ProcessDeltaQueue();
					Item.ProcessDeltaQueue();

					Timer.Slice();
					m_MessagePump.Slice();

					NetState.FlushAll();
					NetState.ProcessDisposedQueue();

					if (Slice != null)
						Slice();
				}
#if !DEBUG
			}
			catch (Exception e)
			{
				CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, true));
			}
#endif

		}
コード例 #10
0
ファイル: Main.cs プロジェクト: greeduomacro/UO-Forever
		public static void Main( string[] args )
		{
			AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler( CurrentDomain_UnhandledException );
			AppDomain.CurrentDomain.ProcessExit += new EventHandler( CurrentDomain_ProcessExit );

			for( int i = 0; i < args.Length; ++i )
			{
				if ( Insensitive.Equals( args[i], "-debug" ) )
					m_Debug = true;
				else if ( Insensitive.Equals( args[i], "-service" ) )
					m_Service = true;
				else if ( Insensitive.Equals( args[i], "-profile" ) )
					Profiling = true;
				else if ( Insensitive.Equals( args[i], "-nocache" ) )
					m_Cache = false;
				else if ( Insensitive.Equals( args[i], "-haltonwarning" ) )
					m_HaltOnWarning = true;
				else if ( Insensitive.Equals( args[i], "-vb" ) )
					m_VBdotNET = true;
				else if ( Insensitive.Equals( args[i], "-publish" ) )
					m_Publish = true;
			}

			try
			{
				if( m_Service )
				{
					if( !Directory.Exists( "Logs" ) )
						Directory.CreateDirectory( "Logs" );

					Console.SetOut( m_MultiConOut = new MultiTextWriter( new FileLogger( "Logs/Console.log" ) ) );
				}
				else
				{
					Console.SetOut( m_MultiConOut = new MultiTextWriter( Console.Out ) );
				}
			}
			catch
			{
			}

			m_Thread = Thread.CurrentThread;
			m_Process = Process.GetCurrentProcess();
			m_Assembly = Assembly.GetEntryAssembly();

			if( m_Thread != null )
				m_Thread.Name = "Core Thread";

			if( BaseDirectory.Length > 0 )
				Directory.SetCurrentDirectory( BaseDirectory );

			Timer.TimerThread ttObj = new Timer.TimerThread();
			timerThread = new Thread( new ThreadStart( ttObj.TimerMain ) );
			timerThread.Name = "Timer Thread";

			Version ver = m_Assembly.GetName().Version;

			string svn = string.Empty;

			if ( File.Exists( "Data/RunUO_SVN.cfg" ) )
			{
				using ( StreamReader ip = new StreamReader( "Data/RunUO_SVN.cfg" ) )
				{
					svn = ip.ReadLine();
				}
			}

			// Added to help future code support on forums, as a 'check' people can ask for to it see if they recompiled core or not
			Utility.PushColor( ConsoleColor.Green );
			Console.WriteLine( "RunUO - [www.runuo.com] Version {0}.{1}, {2}{3}", ver.Major, ver.Minor, svn != String.Empty ? "SVN rev. " : String.Empty, svn );
			Utility.PopColor();
#if Mono
			string version = "MONO";
#else
			string version = Environment.Version.ToString();
#endif
			Console.WriteLine( "Core: Running on .NET Framework Version {0}", version );

			string s = Arguments;

			if( s.Length > 0 )
				Console.WriteLine( "Core: Running with arguments: {0}", s );

			m_ProcessorCount = Environment.ProcessorCount;

			if( m_ProcessorCount > 1 )
				m_MultiProcessor = true;

			if( m_MultiProcessor || Is64Bit )
				Console.WriteLine( "Core: Optimizing for {0} {2}processor{1}", m_ProcessorCount, m_ProcessorCount == 1 ? "" : "s", Is64Bit ? "64-bit " : "" );

			int platform = (int)Environment.OSVersion.Platform;
			if( platform == 4 || platform == 128 ) { // MS 4, MONO 128
				m_Unix = true;
				Console.WriteLine( "Core: Unix environment detected" );
			}
			else {
				m_ConsoleEventHandler = new ConsoleEventHandler( OnConsoleEvent );
				SetConsoleCtrlHandler( m_ConsoleEventHandler, true );
			}

            if ( GCSettings.IsServerGC )
                Console.WriteLine("Core: Server garbage collection mode enabled");


			if ( File.Exists( "Data/Culture.cfg" ) )
			{
				using ( StreamReader ip = new StreamReader( "Data/Culture.cfg" ) )
				{
					string line = ip.ReadLine();
					if ( !String.IsNullOrEmpty( line ) )
					{
						m_Thread.CurrentCulture = new CultureInfo( line );
						Console.WriteLine( "Core: Culture modified to {0}", m_Thread.CurrentCulture.NativeName );
					}
				}
			}

			while( !ScriptCompiler.Compile( m_Debug, m_Cache, m_Publish ) )
			{
				Console.WriteLine( "Scripts: One or more scripts failed to compile or no script files were found." );

				if( m_Publish || m_Service )
					return;

				Console.WriteLine( " - Press return to exit, or R to try again." );

				if( Console.ReadKey( true ).Key != ConsoleKey.R )
					return;
			}

			ScriptCompiler.Invoke( "Configure" );

			Console.Write( "Core: Initializing localization strings..." );
			ClilocHandler.AddCliloc( "ENU" ); //English - No Argument sets the default
			ClilocHandler.AddCliloc( "CHS" ); //Chinese
			ClilocHandler.AddCliloc( "CHT" ); //Chinese
			ClilocHandler.AddCliloc( "DEU" ); //German
			ClilocHandler.AddCliloc( "ESP" ); //Spanish
			ClilocHandler.AddCliloc( "FRA" ); //French
			ClilocHandler.AddCliloc( "JPN" ); //Japan
			ClilocHandler.AddCliloc( "KOR" ); //Korean
			Console.WriteLine( "done ({0} languages)", StringList.StringLists.Count );

			Region.Load();
			World.Load();

			ScriptCompiler.Invoke( "Initialize" );

			MessagePump messagePump = new MessagePump();

			timerThread.Start();

			for( int i = 0; i < Map.AllMaps.Count; ++i )
				Map.AllMaps[i].Tiles.Force();

			NetState.Initialize();

			EventSink.InvokeServerStarted();

			try
			{
				DateTime now, last = DateTime.UtcNow;

				const int sampleInterval = 100;
				//const float ticksPerSecond = (float)(TimeSpan.TicksPerSecond * sampleInterval);
                const float ticksPerSecond = (float)(1000 * sampleInterval);

				long sample = 0;

				while( m_Signal.WaitOne() )
				{
					Mobile.ProcessDeltaQueue();
					Item.ProcessDeltaQueue();

					Timer.Slice();
					messagePump.Slice();

					NetState.FlushAll();
					NetState.ProcessDisposedQueue();

					if( Slice != null )
						Slice();

					if( (++sample % sampleInterval) == 0 )
					{
						now = DateTime.UtcNow;
						m_CyclesPerSecond[m_CycleIndex++ % m_CyclesPerSecond.Length] =
							ticksPerSecond / (now.Ticks - last.Ticks);
						last = now;
					}
				}
			}
			catch( Exception e )
			{
				CurrentDomain_UnhandledException( null, new UnhandledExceptionEventArgs( e, true ) );
			}
		}
コード例 #11
0
ファイル: Main.cs プロジェクト: mikkelhartmann/ServUO
 public static extern bool SetConsoleCtrlHandler(ConsoleEventHandler callback, bool add);
コード例 #12
0
ファイル: Main.cs プロジェクト: rokann/JustUO
			internal static extern bool SetConsoleCtrlHandler(ConsoleEventHandler callback, bool add);
コード例 #13
0
ファイル: Core.cs プロジェクト: GodLesZ/svn-dump
		public static void Main( string[] args ) {
#if !DEBUG
			AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler( CurrentDomain_UnhandledException );
#endif
			AppDomain.CurrentDomain.ProcessExit += new EventHandler( CurrentDomain_ProcessExit );

			try {

				mThread = Thread.CurrentThread;
				mProcess = Process.GetCurrentProcess();
				mAssembly = Assembly.GetEntryAssembly();
				if( mThread != null )
					mThread.Name = "Core Thread";

				Timer.TimerThread ttObj = new Timer.TimerThread();
				mTimerThread = new Thread( new ThreadStart( ttObj.TimerMain ) );
				mTimerThread.Name = "Timer Thread";

				int width = Math.Min( 100, Console.LargestWindowWidth - 2 );
				Console.CursorVisible = false;
				Console.Clear();
				Console.WindowLeft = Console.WindowTop = 0;
				if( Console.WindowWidth < width )
					Console.WindowWidth = width;

				LogoPrinter.PrefixColor = EConsoleColor.Blue;
				LogoPrinter.SufixColor = EConsoleColor.Blue;
				LogoPrinter.TextColor = EConsoleColor.Gray;
				LogoPrinter.PrintLogo();
	
				Version ver = mAssembly.GetName().Version;
				CConsole.StatusLine( "Shaiya.Extended Server - Version {0}.{1}, Build {2}.{3}", ver.Major, ver.Minor, ver.Build, ver.Revision );

				mConsoleEventHandler = new ConsoleEventHandler( OnConsoleEvent );
				SetConsoleCtrlHandler( mConsoleEventHandler, true );

				mAppConf = new ApplicationSettings();
				mAppConf.ReadAll();

				Stopwatch watch = Stopwatch.StartNew();
				CConsole.Info( "Connecting to SQL Server {0}...", mAppConf.Network[ "DB Server" ] );
				mDatabase = new MySqlWrapper( mAppConf.Network[ "DB Server" ], int.Parse( mAppConf.Network[ "DB Port" ] ), mAppConf.Network[ "DB User" ], mAppConf.Network[ "DB Password" ], mAppConf.Network[ "DB Database" ] );
				MysqlError conRes = mDatabase.Prepare();
				if( conRes != MysqlError.None ) {
					CConsole.WriteLine( EConsoleColor.Error, " failed!" );
					throw new Exception( "Failed to open Database Connection! Type: " + conRes.ToString() );
				}
				watch.Stop();
				CConsole.WriteLine( EConsoleColor.Status, " done! Needed {0:F2} sec", watch.Elapsed.TotalSeconds );
				watch = null;

				ScriptDatabase.Initialize( @"Scripts\ScriptList.xml" );
				ScriptCompiler.Compile( AppDomain.CurrentDomain.BaseDirectory + Path.Combine( Settings.Default.MainConfDir, Settings.Default.ScriptAssemblies ), true, true );

				World.Load();

				// testing CallMethod
				ScriptCompiler.CallMethod( "Initialize" );

				SocketPool.Create();
				mSocketConnector = new SocketConnector( mAppConf.Network[ "Server IP" ], mAppConf.Network.GetInt( "Server Port" ) );
				PacketHandlers.Initialize();

				// start Timer Thread
				mTimerThread.Start();

				NetState.Initialize();

				// finished Loading
				Events.InvokeServerStarted();


				DateTime now, last = DateTime.Now;
				const int sampleInterval = 100;
				const float ticksPerSecond = (float)( TimeSpan.TicksPerSecond * sampleInterval );
				int sample = 0;

				while( mSignal.WaitOne() ) {
					Timer.Slice();
					mSocketConnector.Slice();

					NetState.FlushAll();
					NetState.ProcessDisposedQueue();

					if( Slice != null )
						Slice();

					// just for Diagnostics
					if( ( ++sample % sampleInterval ) == 0 ) {
						now = DateTime.Now;
						mCyclesPerSecond[ mCycleIndex++ % mCyclesPerSecond.Length ] = ticksPerSecond / ( now.Ticks - last.Ticks );
						last = now;
					}
				}
			} catch( Exception e ) {
				CurrentDomain_UnhandledException( null, new UnhandledExceptionEventArgs( e, true ) );
			}

		}
コード例 #14
0
ファイル: Main.cs プロジェクト: Leodinas/uolite
		public static void Main( string[] args )
		{
			AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler( CurrentDomain_UnhandledException );
			AppDomain.CurrentDomain.ProcessExit += new EventHandler( CurrentDomain_ProcessExit );

			for( int i = 0; i < args.Length; ++i )
			{
				if ( Insensitive.Equals( args[i], "-debug" ) )
					m_Debug = true;
				else if ( Insensitive.Equals( args[i], "-service" ) )
					m_Service = true;
				else if ( Insensitive.Equals( args[i], "-profile" ) )
					Profiling = true;
				else if ( Insensitive.Equals( args[i], "-nocache" ) )
					m_Cache = false;
				else if ( Insensitive.Equals( args[i], "-haltonwarning" ) )
					m_HaltOnWarning = true;
				else if ( Insensitive.Equals( args[i], "-vb" ) )
					m_VBdotNET = true;
			}

			try
			{
				if( m_Service )
				{
					if( !Directory.Exists( "Logs" ) )
						Directory.CreateDirectory( "Logs" );

					Console.SetOut( m_MultiConOut = new MultiTextWriter( new FileLogger( "Logs/Console.log" ) ) );
				}
				else
				{
					Console.SetOut( m_MultiConOut = new MultiTextWriter( Console.Out ) );
				}
			}
			catch
			{
			}

			m_Thread = Thread.CurrentThread;
			m_Process = Process.GetCurrentProcess();
			m_Assembly = Assembly.GetEntryAssembly();

			if( m_Thread != null )
				m_Thread.Name = "Core Thread";

			if( BaseDirectory.Length > 0 )
				Directory.SetCurrentDirectory( BaseDirectory );

			Timer.TimerThread ttObj = new Timer.TimerThread();
			timerThread = new Thread( new ThreadStart( ttObj.TimerMain ) );
			timerThread.Name = "Timer Thread";

			Version ver = m_Assembly.GetName().Version;

			// Added to help future code support on forums, as a 'check' people can ask for to it see if they recompiled core or not
			Console.WriteLine( "RunUO - [www.runuo.com] Version {0}.{1}, Build {2}.{3}", ver.Major, ver.Minor, ver.Build, ver.Revision );
			Console.WriteLine( "Core: Running on .NET Framework Version {0}.{1}.{2}", Environment.Version.Major, Environment.Version.Minor, Environment.Version.Build );

			string s = Arguments;

			if( s.Length > 0 )
				Console.WriteLine( "Core: Running with arguments: {0}", s );

			m_ProcessorCount = Environment.ProcessorCount;

			if( m_ProcessorCount > 1 )
				m_MultiProcessor = true;

			if( m_MultiProcessor || Is64Bit )
				Console.WriteLine( "Core: Optimizing for {0} {2}processor{1}", m_ProcessorCount, m_ProcessorCount == 1 ? "" : "s", Is64Bit ? "64-bit " : "" );

			int platform = (int)Environment.OSVersion.Platform;
			if( platform == 4 || platform == 128 ) { // MS 4, MONO 128
				m_Unix = true;
				Console.WriteLine( "Core: Unix environment detected" );
			}
			else {
				m_ConsoleEventHandler = new ConsoleEventHandler( OnConsoleEvent );
				SetConsoleCtrlHandler( m_ConsoleEventHandler, true );
			}

			if ( GCSettings.IsServerGC )
				Console.WriteLine("Core: Server garbage collection mode enabled");

			while( !ScriptCompiler.Compile( m_Debug, m_Cache ) )
			{
				Console.WriteLine( "Scripts: One or more scripts failed to compile or no script files were found." );
				
				if( m_Service )
					return;

				Console.WriteLine( " - Press return to exit, or R to try again." );
				
				if( Console.ReadKey( true ).Key != ConsoleKey.R )
					return;
			}

			ScriptCompiler.Invoke( "Configure" );
			
			Region.Load();
			World.Load();

			ScriptCompiler.Invoke( "Initialize" );

			MessagePump ms = m_MessagePump = new MessagePump();

			timerThread.Start();

			for( int i = 0; i < Map.AllMaps.Count; ++i )
				Map.AllMaps[i].Tiles.Force();

			NetState.Initialize();

			EventSink.InvokeServerStarted();

			try
			{
				DateTime now, last = DateTime.Now;

				const int sampleInterval = 100;
				const float ticksPerSecond = (float)(TimeSpan.TicksPerSecond * sampleInterval);

				long sample = 0;

				while( m_Signal.WaitOne() )
				{
					Mobile.ProcessDeltaQueue();
					Item.ProcessDeltaQueue();

					Timer.Slice();
					m_MessagePump.Slice();

					NetState.FlushAll();
					NetState.ProcessDisposedQueue();

					if( Slice != null )
						Slice();

					if( (++sample % sampleInterval) == 0 )
					{
						now = DateTime.Now;
						m_CyclesPerSecond[m_CycleIndex++ % m_CyclesPerSecond.Length] =
							ticksPerSecond / (now.Ticks - last.Ticks);
						last = now;
					}
				}
			}
			catch( Exception e )
			{
				CurrentDomain_UnhandledException( null, new UnhandledExceptionEventArgs( e, true ) );
			}
		}
コード例 #15
0
ファイル: Main.cs プロジェクト: felladrin/runuo-pt-br
        public static void Main( string[] args )
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;

            foreach (string a in args)
            {
                if ( Insensitive.Equals( a, "-debug" ) )
                    m_Debug = true;
                else if ( Insensitive.Equals( a, "-service" ) )
                    m_Service = true;
                else if ( Insensitive.Equals( a, "-profile" ) )
                    Profiling = true;
                else if ( Insensitive.Equals( a, "-nocache" ) )
                    m_Cache = false;
                else if ( Insensitive.Equals( a, "-haltonwarning" ) )
                    m_HaltOnWarning = true;
                else if ( Insensitive.Equals( a, "-vb" ) )
                    m_VBdotNET = true;
                else if ( Insensitive.Equals( a, "-usehrt" ) )
                    _UseHRT = true;
            }

            try
            {
                if( m_Service )
                {
                    if( !Directory.Exists( "Logs" ) )
                        Directory.CreateDirectory( "Logs" );

                    Console.SetOut( m_MultiConOut = new MultiTextWriter( new FileLogger( "Logs/Console.log" ) ) );
                }
                else
                {
                    Console.SetOut( m_MultiConOut = new MultiTextWriter( Console.Out ) );
                }
            }
            catch
            {
            }

            m_Thread = Thread.CurrentThread;
            m_Process = Process.GetCurrentProcess();
            m_Assembly = Assembly.GetEntryAssembly();

            if( m_Thread != null )
                m_Thread.Name = "Core Thread";

            if( BaseDirectory.Length > 0 )
                Directory.SetCurrentDirectory( BaseDirectory );

            Timer.TimerThread ttObj = new Timer.TimerThread();
            timerThread = new Thread(ttObj.TimerMain)
            {
                Name = "Timer Thread"
            };

            Version ver = m_Assembly.GetName().Version;

            // Added to help future code support on forums, as a 'check' people can ask for to it see if they recompiled core or not
            Console.WriteLine("RunUO - [https://github.com/runuo/] Versão {0}.{1}.{2}.{3}", ver.Major, ver.Minor, ver.Build, ver.Revision);
            Console.WriteLine("Core: Rodando em .NET Framework Versão {0}.{1}.{2}", Environment.Version.Major, Environment.Version.Minor, Environment.Version.Build);

            string s = Arguments;

            if( s.Length > 0 )
                Console.WriteLine( "Core: Rodando com argumentos: {0}", s );

            m_ProcessorCount = Environment.ProcessorCount;

            if( m_ProcessorCount > 1 )
                m_MultiProcessor = true;

            if( m_MultiProcessor || Is64Bit )
                Console.WriteLine( "Core: Otimizando para {0} processador{1} {2}", m_ProcessorCount, m_ProcessorCount == 1 ? "" : "es", Is64Bit ? "64-bit" : "" );

            int platform = (int)Environment.OSVersion.Platform;
            if( platform == 4 || platform == 128 ) { // MS 4, MONO 128
                m_Unix = true;
                Console.WriteLine( "Core: Ambiente Unix detectado" );
            }
            else {
                m_ConsoleEventHandler = OnConsoleEvent;
                UnsafeNativeMethods.SetConsoleCtrlHandler( m_ConsoleEventHandler, true );
            }

            if ( GCSettings.IsServerGC )
                Console.WriteLine("Core: Coleta de lixo habilitada no servidor");

            if (_UseHRT)
                Console.WriteLine("Core: Requested high resolution timing ({0})", UsingHighResolutionTiming ? "Supported" : "Unsupported");

            Console.WriteLine("RandomImpl: {0} ({1})", RandomImpl.Type.Name, RandomImpl.IsHardwareRNG ? "Hardware" : "Software");

            while( !ScriptCompiler.Compile( m_Debug, m_Cache ) )
            {
                Console.WriteLine( "Scripts: Um ou mais scripts nao puderam ser compilados ou nenhum script foi encontrado." );

                if( m_Service )
                    return;

                Console.WriteLine( " - Pressione ENTER para sair, ou R para tentar novamente." );

                if( Console.ReadKey( true ).Key != ConsoleKey.R )
                    return;
            }

            ScriptCompiler.Invoke( "Configure" );

            Region.Load();
            World.Load();

            ScriptCompiler.Invoke( "Initialize" );

            MessagePump messagePump = m_MessagePump = new MessagePump();

            timerThread.Start();

            foreach (Map m in Map.AllMaps)
                m.Tiles.Force();

            NetState.Initialize();

            EventSink.InvokeServerStarted();

            try
            {
                long now, last = TickCount;

                const int sampleInterval = 100;
                const float ticksPerSecond = 1000.0f * sampleInterval;

                long sample = 0;

                while( !m_Closing )
                {
                    m_Signal.WaitOne();

                    Mobile.ProcessDeltaQueue();
                    Item.ProcessDeltaQueue();

                    Timer.Slice();
                    messagePump.Slice();

                    NetState.FlushAll();
                    NetState.ProcessDisposedQueue();

                    if( Slice != null )
                        Slice();

                    if (sample++ % sampleInterval != 0)
                    {
                        continue;
                    }

                    now = TickCount;
                    m_CyclesPerSecond[m_CycleIndex++ % m_CyclesPerSecond.Length] = ticksPerSecond / (now - last);
                    last = now;
                }
            }
            catch( Exception e )
            {
                CurrentDomain_UnhandledException( null, new UnhandledExceptionEventArgs( e, true ) );
            }
        }
コード例 #16
0
ファイル: Main.cs プロジェクト: OrbitStorm/Defiance-UOR-1.10
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            AppDomain.CurrentDomain.ProcessExit        += new EventHandler(CurrentDomain_ProcessExit);

            for (int i = 0; i < args.Length; ++i)
            {
                if (Insensitive.Equals(args[i], "-debug"))
                {
                    m_Debug = true;
                }
                else if (Insensitive.Equals(args[i], "-service"))
                {
                    m_Service = true;
                }
                else if (Insensitive.Equals(args[i], "-profile"))
                {
                    Profiling = true;
                }
                else if (Insensitive.Equals(args[i], "-nocache"))
                {
                    m_Cache = false;
                }
                else if (Insensitive.Equals(args[i], "-haltonwarning"))
                {
                    m_HaltOnWarning = true;
                }
                else if (Insensitive.Equals(args[i], "-vb"))
                {
                    m_VBdotNET = true;
                }
                else if (Insensitive.Equals(args[i], "-publish"))
                {
                    m_Publish = true;
                }
            }

            try
            {
                if (m_Service)
                {
                    if (!Directory.Exists("Logs"))
                    {
                        Directory.CreateDirectory("Logs");
                    }

                    Console.SetOut(m_MultiConOut = new MultiTextWriter(new FileLogger("Logs/Console.log")));
                }
                else
                {
                    Console.SetOut(m_MultiConOut = new MultiTextWriter(Console.Out));
                }
            }
            catch
            {
            }

            m_Thread   = Thread.CurrentThread;
            m_Process  = Process.GetCurrentProcess();
            m_Assembly = Assembly.GetEntryAssembly();

            if (m_Thread != null)
            {
                m_Thread.Name = "Core Thread";
            }

            if (BaseDirectory.Length > 0)
            {
                Directory.SetCurrentDirectory(BaseDirectory);
            }

            Timer.TimerThread ttObj = new Timer.TimerThread();
            timerThread      = new Thread(new ThreadStart(ttObj.TimerMain));
            timerThread.Name = "Timer Thread";

            Version ver = m_Assembly.GetName().Version;

            // Added to help future code support on forums, as a 'check' people can ask for to it see if they recompiled core or not
            Console.WriteLine("RunUO - [www.runuo.com] Version {0}.{1}, Build {2}.{3}", ver.Major, ver.Minor, ver.Build, ver.Revision);
#if Framework_3_5
            string version = "3.5";
#elif Mono
            string version = "MONO";
#else
            string version = Environment.Version.ToString();
#endif
            Console.WriteLine("Core: Running on .NET Framework Version {0}", version);

            string s = Arguments;

            if (s.Length > 0)
            {
                Console.WriteLine("Core: Running with arguments: {0}", s);
            }

            m_ProcessorCount = Environment.ProcessorCount;

            if (m_ProcessorCount > 1)
            {
                m_MultiProcessor = true;
            }

            if (m_MultiProcessor || Is64Bit)
            {
                Console.WriteLine("Core: Optimizing for {0} {2}processor{1}", m_ProcessorCount, m_ProcessorCount == 1 ? "" : "s", Is64Bit ? "64-bit " : "");
            }

            int platform = (int)Environment.OSVersion.Platform;
            if (platform == 4 || platform == 128)                // MS 4, MONO 128
            {
                m_Unix = true;
                Console.WriteLine("Core: Unix environment detected");
            }
            else
            {
                m_ConsoleEventHandler = new ConsoleEventHandler(OnConsoleEvent);
                SetConsoleCtrlHandler(m_ConsoleEventHandler, true);
            }

            if (GCSettings.IsServerGC)
            {
                Console.WriteLine("Core: Server garbage collection mode enabled");
            }


            if (File.Exists("Data/Culture.cfg"))
            {
                using (StreamReader ip = new StreamReader("Data/Culture.cfg"))
                {
                    string line = ip.ReadLine();
                    if (!String.IsNullOrEmpty(line))
                    {
                        m_Thread.CurrentCulture = new CultureInfo(line);
                        Console.WriteLine("Core: Culture modified to {0}", m_Thread.CurrentCulture.NativeName);
                    }
                }
            }

            while (!ScriptCompiler.Compile(m_Debug, m_Cache, m_Publish))
            {
                Console.WriteLine("Scripts: One or more scripts failed to compile or no script files were found.");

                if (m_Publish || m_Service)
                {
                    return;
                }

                Console.WriteLine(" - Press return to exit, or R to try again.");

                if (Console.ReadKey(true).Key != ConsoleKey.R)
                {
                    return;
                }
            }

            ScriptCompiler.Invoke("Configure");

            Console.Write("Core: Initializing localization strings...");
            ClilocHandler.AddCliloc("ENU");               //English - No Argument sets the default
            ClilocHandler.AddCliloc("CHS");               //Chinese
            ClilocHandler.AddCliloc("CHT");               //Chinese
            ClilocHandler.AddCliloc("DEU");               //German
            ClilocHandler.AddCliloc("ESP");               //Spanish
            ClilocHandler.AddCliloc("FRA");               //French
            ClilocHandler.AddCliloc("JPN");               //Japan
            ClilocHandler.AddCliloc("KOR");               //Korean
            Console.WriteLine("done ({0} languages)", StringList.StringLists.Count);

            Region.Load();
            World.Load();

            ScriptCompiler.Invoke("Initialize");

            MessagePump ms = m_MessagePump = new MessagePump();

            timerThread.Start();

            for (int i = 0; i < Map.AllMaps.Count; ++i)
            {
                Map.AllMaps[i].Tiles.Force();
            }

            NetState.Initialize();

            EventSink.InvokeServerStarted();

            try
            {
                DateTime now, last = DateTime.Now;

                const int   sampleInterval = 100;
                const float ticksPerSecond = (float)(TimeSpan.TicksPerSecond * sampleInterval);

                long sample = 0;

                while (m_Signal.WaitOne())
                {
                    Mobile.ProcessDeltaQueue();
                    Item.ProcessDeltaQueue();

                    Timer.Slice();
                    m_MessagePump.Slice();

                    NetState.FlushAll();
                    NetState.ProcessDisposedQueue();

                    if (Slice != null)
                    {
                        Slice();
                    }

                    if ((++sample % sampleInterval) == 0)
                    {
                        now = DateTime.Now;
                        m_CyclesPerSecond[m_CycleIndex++ % m_CyclesPerSecond.Length] =
                            ticksPerSecond / (now.Ticks - last.Ticks);
                        last = now;
                    }
                }
            }
            catch (Exception e)
            {
                CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, true));
            }
        }
コード例 #17
0
ファイル: Console.cs プロジェクト: BenVlodgi/CommandHelper
        public static string ReadLine(string input = "", ConsoleEventHandler onTab = null)
        {
            int startLeft = System.Console.CursorLeft;
            int startTop = System.Console.CursorTop;

            int relativeLeft = input.Length;

            while (true)
            {
                RedrawConsoleInput(input, startLeft, startTop);

                //System.Console.CursorLeft = startLeft + relativeLeft;

                int trl = startLeft + relativeLeft;
                System.Console.CursorLeft = trl % System.Console.WindowWidth;
                System.Console.CursorTop = trl / System.Console.WindowWidth + startTop;

                System.Console.CursorVisible = true;
                var key = System.Console.ReadKey(true);
                System.Console.CursorVisible = false;
                if (key.Key == ConsoleKey.Enter)
                    return input;
                else if (key.Key == ConsoleKey.Tab)
                {
                    if (onTab != null)
                    {
                        ConsoleEventArgs e = new ConsoleEventArgs(relativeLeft, input);
                        onTab(null, e);
                        if (e.Update)
                        {
                            relativeLeft = e.CursorLeft;
                            input = e.Input;
                        }
                    }
                }
                else if (key.Key == ConsoleKey.LeftArrow)
                {
                    if (relativeLeft > 0)
                        relativeLeft--;
                }
                else if (key.Key == ConsoleKey.RightArrow)
                {
                    if (relativeLeft < input.Length)
                        relativeLeft++;
                }
                else if (key.Key == ConsoleKey.Backspace)
                {
                    if (relativeLeft > 0)
                    {
                        relativeLeft--;
                        input = input.Remove(relativeLeft, 1);
                        RedrawConsoleInput(input, startLeft, startTop);
                    }
                }
                else if (key.Key == ConsoleKey.Delete)
                {
                    if (relativeLeft < input.Length)
                    {
                        input = input.Remove(relativeLeft, 1);
                        RedrawConsoleInput(input, startLeft, startTop);
                    }
                }
                else if (key.Key == ConsoleKey.Insert)
                {
                    // Can't enable insert mode.   
                }
                else if (key.Key == ConsoleKey.End)
                {
                    relativeLeft = input.Length;
                }
                else if (key.Key == ConsoleKey.Home)
                {
                    relativeLeft = 0;
                }
                else
                {
                    if (key.KeyChar != '\0')
                    {
                        input = input.Insert(relativeLeft, key.KeyChar.ToString());
                        RedrawConsoleInput(input, startLeft, startTop);
                        relativeLeft++;
                    }
                }

            }
        }
コード例 #18
0
 public static void Listen()
 {
     handler += OnConsoleEvent;
       SetConsoleCtrlHandler(handler, true);
 }
コード例 #19
0
        internal static void Run()
        {
            Properties.Settings.Default.SettingsLoaded += Default_SettingsLoaded;

            InitializeLogging();

            Console.WriteLine("Starting...");

            m_Thread = Thread.CurrentThread;
            m_Process = Process.GetCurrentProcess();

            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
            m_Assembly = Assembly.GetEntryAssembly();

            if (m_Thread != null)
                m_Thread.Name = "Core Thread";

            Timer.TimerThread ttObj = new Timer.TimerThread();
            timerThread = new Thread(new ThreadStart(ttObj.TimerMain));
            timerThread.Name = "Timer Thread";

            Version ver = m_Assembly.GetName().Version;

            Timer.DelayCall(TimeSpan.FromSeconds(5.0), () => { Console.WriteLine("RPC Timeout: {0} seconds.", NamecoinLib.RPC.RpcConnector.RpcRequestTimeoutInSeconds); });

            Configure();

            Initialize();

            m_ConsoleEventHandler = new ConsoleEventHandler(OnConsoleEvent);
            SetConsoleCtrlHandler(m_ConsoleEventHandler, true);

            timerThread.Start();

            try
            {
                DateTime now, last = DateTime.UtcNow;

                const int sampleInterval = 100;
                const float ticksPerSecond = (float)(TimeSpan.TicksPerSecond * sampleInterval);
                TimeSpan _oneMS = TimeSpan.FromMilliseconds(1);

                long sample = 0;

                while (!m_Closing)
                {
                    m_Signal.WaitOne(_oneMS);
                    Timer.Slice();
                    if (Slice != null)
                        Slice();
                    if ((++sample % sampleInterval) == 0)
                    {
                        now = DateTime.UtcNow;
                        m_CyclesPerSecond[m_CycleIndex++ % m_CyclesPerSecond.Length] =
                            ticksPerSecond / (now.Ticks - last.Ticks);
                        last = now;
                    }
                }
            }
            catch (Exception e)
            {
                CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, true));
            }
            finally
            {
                UI.Monitor.DisableCacheEntries();
            }
        }
コード例 #20
0
ファイル: Main.cs プロジェクト: BackupTheBerlios/sunuo-svn
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            AppDomain.CurrentDomain.ProcessExit        += new EventHandler(CurrentDomain_ProcessExit);

            bool debug = false;

            for (int i = 0; i < args.Length; ++i)
            {
                if (Insensitive.Equals(args[i], "-debug"))
                {
                    debug = true;
                }
                else if (Insensitive.Equals(args[i], "-service"))
                {
                    m_Service = true;
                }
                else if (Insensitive.Equals(args[i], "-profile"))
                {
                    Profiling = true;
                }
            }

            try
            {
                if (m_Service)
                {
                    if (!Directory.Exists("Logs"))
                    {
                        Directory.CreateDirectory("Logs");
                    }

                    Console.SetOut(m_MultiConOut = new MultiTextWriter(Console.Out, new FileLogger("Logs/Console.log")));
                }
                else
                {
                    Console.SetOut(m_MultiConOut = new MultiTextWriter(Console.Out));
                }
            }
            catch
            {
            }

#if !MONO
            m_ConsoleEventHandler = new ConsoleEventHandler(OnConsoleEvent);
            SetConsoleCtrlHandler(m_ConsoleEventHandler, true);
#endif

            m_Thread   = Thread.CurrentThread;
            m_Process  = Process.GetCurrentProcess();
            m_Assembly = Assembly.GetEntryAssembly();

            if (m_Thread != null)
            {
                m_Thread.Name = "Core Thread";
            }

            if (BaseDirectory.Length > 0)
            {
                Directory.SetCurrentDirectory(BaseDirectory);
            }

            Timer.TimerThread ttObj = new Timer.TimerThread();
            timerThread      = new Thread(new ThreadStart(ttObj.TimerMain));
            timerThread.Name = "Timer Thread";

            Version ver = m_Assembly.GetName().Version;

            // Added to help future code support on forums, as a 'check' people can ask for to it see if they recompiled core or not
            Console.WriteLine("RunUO - [www.runuo.com] Version {0}.{1}.{3}, Build {2}", ver.Major, ver.Minor, ver.Revision, ver.Build);

            while (!ScriptCompiler.Compile(debug))
            {
                Console.WriteLine("Scripts: One or more scripts failed to compile or no script files were found.");
                Console.WriteLine(" - Press return to exit, or R to try again.");

                string line = Console.ReadLine();
                if (line == null || line.ToLower() != "r")
                {
                    return;
                }
            }

            Region.Load();

            MessagePump ms = m_MessagePump = new MessagePump(new Listener(Listener.Port));

            timerThread.Start();

            for (int i = 0; i < Map.AllMaps.Count; ++i)
            {
                ((Map)Map.AllMaps[i]).Tiles.Force();
            }

            NetState.Initialize();

            EventSink.InvokeServerStarted();

            try
            {
                while (!m_Closing)
                {
                    Thread.Sleep(1);

                    Mobile.ProcessDeltaQueue();
                    Item.ProcessDeltaQueue();

                    Timer.Slice();
                    m_MessagePump.Slice();

                    NetState.FlushAll();
                    NetState.ProcessDisposedQueue();

                    if (Slice != null)
                    {
                        Slice();
                    }
                }
            }
            catch (Exception e)
            {
                CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, true));
            }

            if (timerThread.IsAlive)
            {
                timerThread.Abort();
            }
        }
コード例 #21
0
ファイル: Core.cs プロジェクト: GodLesZ/svn-dump
		public static void Main(string[] args) {
			// If we set the exceptionhandler also in debug, VS wont throw them and i cant react in Debug-mode
			// They will be printed to the console interface 
#if !DEBUG
			AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler( CurrentDomain_UnhandledException );
#endif
			AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
#if !DEBUG
			try {
#endif

			// Cleanup before loading any other data
			GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);

			// Save some infos about our thread and assembly
			mThread = Thread.CurrentThread;
			mProcess = Process.GetCurrentProcess();
			mAssembly = Assembly.GetEntryAssembly();
			if (mThread != null) {
				// We set a name on our core thread
				mThread.Name = "Core Thread";
			}

			// Initialize our timer manager
			TimerThread ttObj = new TimerThread();
			mTimerThread = new Thread(new ThreadStart(ttObj.TimerMain));
			mTimerThread.Name = "Timer Thread";

			// Prepare console for a large output
			int width = Math.Min(100, Console.LargestWindowWidth - 2);
			Console.CursorVisible = false;
			Console.Clear();
			Console.WindowLeft = Console.WindowTop = 0;
			if (Console.WindowWidth < width) {
				Console.WindowWidth = width;
			}
		
			// Real fullscreen mode *_*
#if REAL_FULLSCREEN
			IntPtr hConsole = GetStdHandle(-11);
			SetConsoleDisplayMode(hConsole, 0);
#endif

			// Set colors for the logo printer
			LogoPrinter.PrefixColor = EConsoleColor.Blue;
			LogoPrinter.SufixColor = EConsoleColor.Blue;
			LogoPrinter.TextColor = EConsoleColor.Gray;
			LogoPrinter.CopyrightColor = EConsoleColor.Status;
			LogoPrinter.PrintLogo();

			// Output some infos about version and that
			Version ver = mAssembly.GetName().Version;
			ServerConsole.StatusLine("Rovolution Server - Version {0}.{1}.{2}.{3}", ver.Major, ver.Minor, ver.Build, ver.Revision);

			// Set error and exception handler (dll import)
			mConsoleEventHandler = new ConsoleEventHandler(OnConsoleEvent);
			SetConsoleCtrlHandler(mConsoleEventHandler, true);

			// Read server config
			mAppConf = new ApplicationSettings();
			mAppConf.ReadAll();

			// Mysql init
			Stopwatch watch = Stopwatch.StartNew();
			ServerConsole.Info("Connecting to SQL Server {0}...", mAppConf.Connection["DB Server"]);
			mDatabase = new RovolutionDatabase(Conf.Connection["DB Server"], int.Parse(Conf.Connection["DB Port"]), Conf.Connection["DB User"], Conf.Connection["DB Password"], Conf.Connection["DB Database"]);
			GodLesZ.Library.MySql.EMysqlConnectionError conRes = mDatabase.Prepare();
			if (conRes != GodLesZ.Library.MySql.EMysqlConnectionError.None) {
				ServerConsole.WriteLine(EConsoleColor.Error, " failed!");
				throw new Exception("Failed to open Database Connection! Type: " + conRes.ToString() + Environment.NewLine + (mDatabase.LastError != null ? ", Message: " + mDatabase.LastError.Message : ""));
			}
			watch.Stop();
			ServerConsole.WriteLine(EConsoleColor.Status, " done! Needed {0:F2} sec", watch.Elapsed.TotalSeconds);
			watch = null;

			// Load scripts (including events & that)
			ScriptDatabase.Initialize(@"Scripts\ScriptList.xml");

			ScriptCompiler.Compile(AppDomain.CurrentDomain.BaseDirectory + Path.Combine(Settings.Default.MainConfDir, Settings.Default.ScriptAssemblies), true, true);
			// Load assemblies for debug
			// TODO: we should load the assemblies for debugging
			//		 so VS could hijack them and we could debug them at runtime
			//		 also need the *.pdb files for this..

			// Packets handler
			PacketLoader.Initialize();

			// Initialize World events
			ScriptCompiler.Initialize("Rovolution.Server.Scripts");

			// Now we are able load our ressources
			World.Load();

			// Content init done, load Socket pool
			SocketPool.Create();
			mSocketConnector = new SocketConnector(mAppConf.Connection["Server IP"], mAppConf.Connection.GetInt("Server Port"));
			PacketHandlers.Initialize();

			// Start Timer Thread
			mTimerThread.Start();

			// Start timer for checking connections
			NetState.Initialize();


			// Initialize & load finished
			// Clean 
			GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);


			// Trigger ServerStarted event
			Events.InvokeServerStarted();


			DateTime now, last = DateTime.Now;
			const int sampleInterval = 100;
			const float ticksPerSecond = (float)(TimeSpan.TicksPerSecond * sampleInterval);
			int sample = 0;

			// The server loop
			// - looks for new sockets and process all packets
			while (mSignal.WaitOne()) {
				// Refresh timer
				Timer.Slice();

				// Kick out old connections
				NetState.FlushAll();
				NetState.ProcessDisposedQueue();
				// Catch new connections
				mSocketConnector.Slice();

				if (Slice != null)
					Slice();

				// just for Diagnostics
				if ((++sample % sampleInterval) == 0) {
					now = DateTime.Now;
					mCyclesPerSecond[mCycleIndex++ % mCyclesPerSecond.Length] = ticksPerSecond / (now.Ticks - last.Ticks);
					last = now;
				}
			}
#if !DEBUG
			} catch (Exception e) {
				CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, true));
			}
#endif
		}
コード例 #22
0
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            AppDomain.CurrentDomain.ProcessExit        += new EventHandler(CurrentDomain_ProcessExit);

            for (int i = 0; i < args.Length; ++i)
            {
                if (Insensitive.Equals(args[i], "-debug"))
                {
                    m_Debug = true;
                }
                else if (Insensitive.Equals(args[i], "-service"))
                {
                    m_Service = true;
                }
                else if (Insensitive.Equals(args[i], "-profile"))
                {
                    Profiling = true;
                }
            }

            try {
                if (m_Service)
                {
                    if (!Directory.Exists("Logs"))
                    {
                        Directory.CreateDirectory("Logs");
                    }

                    Console.SetOut(m_MultiConOut = new MultiTextWriter(Console.Out, new FileLogger("Logs/Console.log")));
                }
                else
                {
                    Console.SetOut(m_MultiConOut = new MultiTextWriter(Console.Out));
                }
            } catch {
            }

#if !MONO
            m_ConsoleEventHandler = new ConsoleEventHandler(OnConsoleEvent);
            SetConsoleCtrlHandler(m_ConsoleEventHandler, true);
#endif

            m_Thread   = Thread.CurrentThread;
            m_Process  = Process.GetCurrentProcess();
            m_Assembly = Assembly.GetEntryAssembly();

            if (m_Thread != null)
            {
                m_Thread.Name = "Core Thread";
            }

            if (BaseDirectory.Length > 0)
            {
                Directory.SetCurrentDirectory(BaseDirectory);
            }

            Timer.TimerThread ttObj = new Timer.TimerThread();
            timerThread      = new Thread(new ThreadStart(ttObj.TimerMain));
            timerThread.Name = "Timer Thread";

            Version ver = m_Assembly.GetName().Version;

            // Added to help future code support on forums, as a 'check' people can ask for to it see if they recompiled core or not
            Console.WriteLine("RunUO - [www.runuo.com] Version {0}.{1}, Build {2}.{3}", ver.Major, ver.Minor, ver.Build, ver.Revision);
            Console.WriteLine("Core: Running on .NET Framework Version {0}.{1}.{2}", Environment.Version.Major, Environment.Version.Minor, Environment.Version.Build);

            string s = Arguments;

            if (s.Length > 0)
            {
                Console.WriteLine("Core: Running with arguments: {0}", s);
            }

            int processorCount = Environment.ProcessorCount;

            if (processorCount > 1)
            {
                m_MultiProcessor = true;
            }

            if (m_MultiProcessor || Is64Bit)
            {
                Console.WriteLine("Core: Optimizing for {0} {2}processor{1}", processorCount, processorCount == 1 ? "" : "s", Is64Bit ? "64-bit " : "");
            }

            m_ProcessorCount = processorCount;

            while (!ScriptCompiler.Compile(m_Debug))
            {
                Console.WriteLine("Scripts: One or more scripts failed to compile or no script files were found.");
                Console.WriteLine(" - Press return to exit, or R to try again.");

                if (Console.ReadKey(true).Key != ConsoleKey.R)
                {
                    return;
                }
            }

            MessagePump ms = m_MessagePump = new MessagePump(new Listener(Listener.Port));

            timerThread.Start();

            for (int i = 0; i < Map.AllMaps.Count; ++i)
            {
                Map.AllMaps[i].Tiles.Force();
            }

            NetState.Initialize();

            EventSink.InvokeServerStarted();

            try {
                DateTime now, last = DateTime.Now;

                const int   sampleInterval = 100;
                const float ticksPerSecond = ( float )(TimeSpan.TicksPerSecond * sampleInterval);

                int sample = 0;

                while (!m_Closing)
                {
                    Thread.Sleep(m_MultiProcessor ? 0 : 1);

                    Mobile.ProcessDeltaQueue();
                    Item.ProcessDeltaQueue();

                    Timer.Slice();
                    m_MessagePump.Slice();

                    NetState.FlushAll();
                    NetState.ProcessDisposedQueue();

                    if (Slice != null)
                    {
                        Slice();
                    }

                    if ((++sample % sampleInterval) == 0)
                    {
                        now = DateTime.Now;
                        m_CyclesPerSecond[m_CycleIndex++ % m_CyclesPerSecond.Length] =
                            ticksPerSecond / (now.Ticks - last.Ticks);
                        last = now;
                    }
                }
            } catch (Exception e) {
                CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, true));
            }

            if (timerThread.IsAlive)
            {
                timerThread.Abort();
            }
        }
コード例 #23
0
ファイル: APIHelper.cs プロジェクト: l3dlp-sandbox/PowerToys
 public static void SetConsoleControlHandler(ConsoleEventHandler handler, bool addHandler)
 {
     NativeMethods.SetConsoleCtrlHandler(handler, addHandler);
 }
コード例 #24
0
ファイル: Main.cs プロジェクト: marcusdiaz/ServUO
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            AppDomain.CurrentDomain.ProcessExit        += CurrentDomain_ProcessExit;

            foreach (string a in args)
            {
                if (Insensitive.Equals(a, "-debug"))
                {
                    Debug = true;
                }
                else if (Insensitive.Equals(a, "-service"))
                {
                    Service = true;
                }
                else if (Insensitive.Equals(a, "-profile"))
                {
                    Profiling = true;
                }
                else if (Insensitive.Equals(a, "-nocache"))
                {
                    _Cache = false;
                }
                else if (Insensitive.Equals(a, "-haltonwarning"))
                {
                    HaltOnWarning = true;
                }
                else if (Insensitive.Equals(a, "-vb"))
                {
                    VBdotNet = true;
                }
                else if (Insensitive.Equals(a, "-usehrt"))
                {
                    _UseHRT = true;
                }
                else if (Insensitive.Equals(a, "-noconsole"))
                {
                    NoConsole = true;
                }
                else if (Insensitive.Equals(a, "-h") || Insensitive.Equals(a, "-help"))
                {
                    Console.WriteLine("An Ultima Online server emulator written in C# - Visit https://www.servuo.com for more information.\n\n");
                    Console.WriteLine(System.AppDomain.CurrentDomain.FriendlyName + " [Parameter]\n\n");
                    Console.WriteLine("     -debug              Starting ServUO in Debug Mode. Debug Mode is being used in Core and Scripts to give extended inforamtion during runtime.");
                    Console.WriteLine("     -haltonwarning      ServUO halts if any warning is raised during compilation of scripts.");
                    Console.WriteLine("     -h or -help         Displays this help text.");
                    Console.WriteLine("     -nocache            No known effect.");
                    Console.WriteLine("     -noconsole          No user interaction during startup and runtime.");
                    Console.WriteLine("     -profile            Enables profiling allowing to get performance diagnostic information of packets, timers etc. in AdminGump -> Maintenance. Use with caution. This increases server load.");
                    Console.WriteLine("     -service            This parameter should be set if you're running ServUO as a Windows Service. No user interaction. *Windows only*");
                    Console.WriteLine("     -usehrt             Enables High Resolution Timing if requirements are met. Increasing the resolution of the timer. *Windows only*");
                    Console.WriteLine("     -vb                 Enables compilation of VB.NET Scripts. Without this option VB.NET Scripts are skipped.");

                    System.Environment.Exit(0);
                }
            }

            if (!Environment.UserInteractive || Service)
            {
                NoConsole = true;
            }

            try
            {
                if (Service)
                {
                    if (!Directory.Exists("Logs"))
                    {
                        Directory.CreateDirectory("Logs");
                    }

                    Console.SetOut(MultiConsoleOut = new MultiTextWriter(new FileLogger("Logs/Console.log")));
                }
                else
                {
                    Console.SetOut(MultiConsoleOut = new MultiTextWriter(Console.Out));
                }
            }
            catch
            { }

            Thread   = Thread.CurrentThread;
            Process  = Process.GetCurrentProcess();
            Assembly = Assembly.GetEntryAssembly();

            if (Thread != null)
            {
                Thread.Name = "Core Thread";
            }

            if (BaseDirectory.Length > 0)
            {
                Directory.SetCurrentDirectory(BaseDirectory);
            }

            Timer.TimerThread ttObj = new Timer.TimerThread();

            _TimerThread = new Thread(ttObj.TimerMain)
            {
                Name = "Timer Thread"
            };

            Version ver = Assembly.GetName().Version;

            // Added to help future code support on forums, as a 'check' people can ask for to it see if they recompiled core or not
            Utility.PushColor(ConsoleColor.DarkGreen);
            if (!NoConsole)
            {
                Console.WriteLine(new String('-', Console.BufferWidth));
            }
            else
            {
                Console.WriteLine(new String('-', 10));
            }
            Utility.PopColor();
            Utility.PushColor(ConsoleColor.Cyan);
        #if DEBUG
            Console.WriteLine(
                "ServUO - [https://www.servuo.com] Version {0}.{1}, Build {2}.{3} - Debug",
                ver.Major,
                ver.Minor,
                ver.Build,
                ver.Revision);
        #else
            Console.WriteLine(
                "ServUO - [https://www.servuo.com] Version {0}.{1}, Build {2}.{3} - Release",
                ver.Major,
                ver.Minor,
                ver.Build,
                ver.Revision);
        #endif
            Utility.PopColor();

            string s = Arguments;

            if (s.Length > 0)
            {
                Utility.PushColor(ConsoleColor.Yellow);
                Console.WriteLine("Core: Running with arguments: {0}", s);
                Utility.PopColor();
            }

            ProcessorCount = Environment.ProcessorCount;

            if (ProcessorCount > 1)
            {
                MultiProcessor = true;
            }

            if (MultiProcessor || Is64Bit)
            {
                Utility.PushColor(ConsoleColor.Green);
                Console.WriteLine(
                    "Core: Optimizing for {0} {2}processor{1}",
                    ProcessorCount,
                    ProcessorCount == 1 ? "" : "s",
                    Is64Bit ? "64-bit " : "");
                Utility.PopColor();
            }

            string dotnet = null;

            #if NETFX_20
            dotnet = "2.0";
            #endif

            #if NETFX_30
            dotnet = "3.0";
            #endif

            #if NETFX_35
            dotnet = "3.5";
            #endif

            #if NETFX_40
            dotnet = "4.0";
            #endif

            #if NETFX_45
            dotnet = "4.5";
            #endif

            #if NETFX_451
            dotnet = "4.5.1";
            #endif

            #if NETFX_46
            dotnet = "4.6.0";
            #endif

            #if NETFX_461
            dotnet = "4.6.1";
            #endif

            #if NETFX_462
            dotnet = "4.6.2";
            #endif

            #if NETFX_47
            dotnet = "4.7";
            #endif

            #if NETFX_471
            dotnet = "4.7.1";
            #endif

            if (String.IsNullOrEmpty(dotnet))
            {
                dotnet = "MONO/CSC/Unknown";
            }

            Utility.PushColor(ConsoleColor.Green);
            Console.WriteLine("Core: Compiled for .NET {0}", dotnet);
            Utility.PopColor();

            int platform = (int)Environment.OSVersion.Platform;

            if (platform == 4 || platform == 128)
            {
                // MS 4, MONO 128
                Unix = true;
                Utility.PushColor(ConsoleColor.Yellow);
                Console.WriteLine("Core: Unix environment detected");
                Utility.PopColor();
            }
            else
            {
                m_ConsoleEventHandler = OnConsoleEvent;
                UnsafeNativeMethods.SetConsoleCtrlHandler(m_ConsoleEventHandler, true);
            }

            if (GCSettings.IsServerGC)
            {
                Utility.PushColor(ConsoleColor.Green);
                Console.WriteLine("Core: Server garbage collection mode enabled");
                Utility.PopColor();
            }

            if (_UseHRT)
            {
                Utility.PushColor(ConsoleColor.DarkYellow);
                Console.WriteLine(
                    "Core: Requested high resolution timing ({0})",
                    UsingHighResolutionTiming ? "Supported" : "Unsupported");
                Utility.PopColor();
            }

            Utility.PushColor(ConsoleColor.DarkYellow);
            Console.WriteLine("RandomImpl: {0} ({1})", RandomImpl.Type.Name, RandomImpl.IsHardwareRNG ? "Hardware" : "Software");
            Utility.PopColor();

            Utility.PushColor(ConsoleColor.Green);
            Console.WriteLine("Core: Loading config...");
            Config.Load();
            Utility.PopColor();

            while (!ScriptCompiler.Compile(Debug, _Cache))
            {
                Utility.PushColor(ConsoleColor.Red);
                Console.WriteLine("Scripts: One or more scripts failed to compile or no script files were found.");
                Utility.PopColor();

                if (Service)
                {
                    return;
                }

                Console.WriteLine(" - Press return to exit, or R to try again.");

                if (Console.ReadKey(true).Key != ConsoleKey.R)
                {
                    return;
                }
            }

            ScriptCompiler.Invoke("Configure");

            Region.Load();
            World.Load();

            ScriptCompiler.Invoke("Initialize");

            MessagePump messagePump = MessagePump = new MessagePump();

            _TimerThread.Start();

            foreach (Map m in Map.AllMaps)
            {
                m.Tiles.Force();
            }

            NetState.Initialize();

            EventSink.InvokeServerStarted();

            try
            {
                long now, last = TickCount;

                const int   sampleInterval = 100;
                const float ticksPerSecond = 1000.0f * sampleInterval;

                long sample = 0;

                while (!Closing)
                {
                    _Signal.WaitOne();

                    Mobile.ProcessDeltaQueue();
                    Item.ProcessDeltaQueue();

                    Timer.Slice();
                    messagePump.Slice();

                    NetState.FlushAll();
                    NetState.ProcessDisposedQueue();

                    if (Slice != null)
                    {
                        Slice();
                    }

                    if (sample++ % sampleInterval != 0)
                    {
                        continue;
                    }

                    now = TickCount;
                    _CyclesPerSecond[_CycleIndex++ % _CyclesPerSecond.Length] = ticksPerSecond / (now - last);
                    last = now;
                }
            }
            catch (Exception e)
            {
                CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, true));
            }
        }
コード例 #25
0
        public static void Main(string[] args)
        {
            // If we set the exceptionhandler also in debug, VS wont throw them and i cant react in Debug-mode
            // They will be printed to the console interface
#if !DEBUG
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
#endif
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
#if !DEBUG
            try {
#endif

            // Cleanup before loading any other data
            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);

            // Save some infos about our thread and assembly
            mThread   = Thread.CurrentThread;
            mProcess  = Process.GetCurrentProcess();
            mAssembly = Assembly.GetEntryAssembly();
            if (mThread != null)
            {
                // We set a name on our core thread
                mThread.Name = "Core Thread";
            }

            // Initialize our timer manager
            TimerThread ttObj = new TimerThread();
            mTimerThread      = new Thread(new ThreadStart(ttObj.TimerMain));
            mTimerThread.Name = "Timer Thread";

            // Prepare console for a large output
            int width = Math.Min(100, Console.LargestWindowWidth - 2);
            Console.CursorVisible = false;
            Console.Clear();
            Console.WindowLeft = Console.WindowTop = 0;
            if (Console.WindowWidth < width)
            {
                Console.WindowWidth = width;
            }

            // Real fullscreen mode *_*
#if REAL_FULLSCREEN
            IntPtr hConsole = GetStdHandle(-11);
            SetConsoleDisplayMode(hConsole, 0);
#endif

            // Set colors for the logo printer
            LogoPrinter.PrefixColor    = EConsoleColor.Blue;
            LogoPrinter.SufixColor     = EConsoleColor.Blue;
            LogoPrinter.TextColor      = EConsoleColor.Gray;
            LogoPrinter.CopyrightColor = EConsoleColor.Status;
            LogoPrinter.PrintLogo();

            // Output some infos about version and that
            Version ver = mAssembly.GetName().Version;
            ServerConsole.StatusLine("Rovolution Server - Version {0}.{1}.{2}.{3}", ver.Major, ver.Minor, ver.Build, ver.Revision);

            // Set error and exception handler (dll import)
            mConsoleEventHandler = new ConsoleEventHandler(OnConsoleEvent);
            SetConsoleCtrlHandler(mConsoleEventHandler, true);

            // Read server config
            mAppConf = new ApplicationSettings();
            mAppConf.ReadAll();

            // Mysql init
            Stopwatch watch = Stopwatch.StartNew();
            ServerConsole.Info("Connecting to SQL Server {0}...", mAppConf.Connection["DB Server"]);
            mDatabase = new RovolutionDatabase(Conf.Connection["DB Server"], int.Parse(Conf.Connection["DB Port"]), Conf.Connection["DB User"], Conf.Connection["DB Password"], Conf.Connection["DB Database"]);
            GodLesZ.Library.MySql.EMysqlConnectionError conRes = mDatabase.Prepare();
            if (conRes != GodLesZ.Library.MySql.EMysqlConnectionError.None)
            {
                ServerConsole.WriteLine(EConsoleColor.Error, " failed!");
                throw new Exception("Failed to open Database Connection! Type: " + conRes.ToString() + Environment.NewLine + (mDatabase.LastError != null ? ", Message: " + mDatabase.LastError.Message : ""));
            }
            watch.Stop();
            ServerConsole.WriteLine(EConsoleColor.Status, " done! Needed {0:F2} sec", watch.Elapsed.TotalSeconds);
            watch = null;

            // Load scripts (including events & that)
            ScriptDatabase.Initialize(@"Scripts\ScriptList.xml");

            ScriptCompiler.Compile(AppDomain.CurrentDomain.BaseDirectory + Path.Combine(Settings.Default.MainConfDir, Settings.Default.ScriptAssemblies), true, true);
            // Load assemblies for debug
            // TODO: we should load the assemblies for debugging
            //		 so VS could hijack them and we could debug them at runtime
            //		 also need the *.pdb files for this..

            // Packets handler
            PacketLoader.Initialize();

            // Initialize World events
            ScriptCompiler.Initialize("Rovolution.Server.Scripts");

            // Now we are able load our ressources
            World.Load();

            // Content init done, load Socket pool
            SocketPool.Create();
            mSocketConnector = new SocketConnector(mAppConf.Connection["Server IP"], mAppConf.Connection.GetInt("Server Port"));
            PacketHandlers.Initialize();

            // Start Timer Thread
            mTimerThread.Start();

            // Start timer for checking connections
            NetState.Initialize();


            // Initialize & load finished
            // Clean
            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);


            // Trigger ServerStarted event
            Events.InvokeServerStarted();


            DateTime now, last = DateTime.Now;
            const int sampleInterval   = 100;
            const float ticksPerSecond = (float)(TimeSpan.TicksPerSecond * sampleInterval);
            int sample = 0;

            // The server loop
            // - looks for new sockets and process all packets
            while (mSignal.WaitOne())
            {
                // Refresh timer
                Timer.Slice();

                // Kick out old connections
                NetState.FlushAll();
                NetState.ProcessDisposedQueue();
                // Catch new connections
                mSocketConnector.Slice();

                if (Slice != null)
                {
                    Slice();
                }

                // just for Diagnostics
                if ((++sample % sampleInterval) == 0)
                {
                    now = DateTime.Now;
                    mCyclesPerSecond[mCycleIndex++ % mCyclesPerSecond.Length] = ticksPerSecond / (now.Ticks - last.Ticks);
                    last = now;
                }
            }
#if !DEBUG
        }

        catch (Exception e) {
            CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, true));
        }
#endif
        }
コード例 #26
0
 public static void Listen()
 {
     handler += OnConsoleEvent;
     SetConsoleCtrlHandler(handler, true);
 }
コード例 #27
0
        internal static void Run()
        {
            Properties.Settings.Default.SettingsLoaded += Default_SettingsLoaded;

            InitializeLogging();

            Console.WriteLine("Starting...");

            m_Thread  = Thread.CurrentThread;
            m_Process = Process.GetCurrentProcess();

            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
            m_Assembly = Assembly.GetEntryAssembly();

            if (m_Thread != null)
            {
                m_Thread.Name = "Core Thread";
            }

            Timer.TimerThread ttObj = new Timer.TimerThread();
            timerThread      = new Thread(new ThreadStart(ttObj.TimerMain));
            timerThread.Name = "Timer Thread";

            Version ver = m_Assembly.GetName().Version;

            Timer.DelayCall(TimeSpan.FromSeconds(5.0), () => { Console.WriteLine("RPC Timeout: {0} seconds.", NamecoinLib.RPC.RpcConnector.RpcRequestTimeoutInSeconds); });

            Configure();

            Initialize();

            m_ConsoleEventHandler = new ConsoleEventHandler(OnConsoleEvent);
            SetConsoleCtrlHandler(m_ConsoleEventHandler, true);

            timerThread.Start();

            try
            {
                DateTime now, last = DateTime.UtcNow;

                const int   sampleInterval = 100;
                const float ticksPerSecond = (float)(TimeSpan.TicksPerSecond * sampleInterval);
                TimeSpan    _oneMS         = TimeSpan.FromMilliseconds(1);

                long sample = 0;

                while (!m_Closing)
                {
                    m_Signal.WaitOne(_oneMS);
                    Timer.Slice();
                    if (Slice != null)
                    {
                        Slice();
                    }
                    if ((++sample % sampleInterval) == 0)
                    {
                        now = DateTime.UtcNow;
                        m_CyclesPerSecond[m_CycleIndex++ % m_CyclesPerSecond.Length] =
                            ticksPerSecond / (now.Ticks - last.Ticks);
                        last = now;
                    }
                }
            }
            catch (Exception e)
            {
                CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, true));
            }
            finally
            {
                UI.Monitor.DisableCacheEntries();
            }
        }
コード例 #28
0
 private static extern bool SetConsoleCtrlHandler(ConsoleEventHandler handler, bool add);
コード例 #29
0
ファイル: Main.cs プロジェクト: ITLongwell/JustUO
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            AppDomain.CurrentDomain.ProcessExit        += CurrentDomain_ProcessExit;

            foreach (string arg in args)
            {
                if (Insensitive.Equals(arg, "-debug"))
                {
                    m_Debug = true;
                }
                else if (Insensitive.Equals(arg, "-service"))
                {
                    m_Service = true;
                }
                else if (Insensitive.Equals(arg, "-profile"))
                {
                    Profiling = true;
                }
                else if (Insensitive.Equals(arg, "-nocache"))
                {
                    m_Cache = false;
                }
                else if (Insensitive.Equals(arg, "-haltonwarning"))
                {
                    m_HaltOnWarning = true;
                }
                else if (Insensitive.Equals(arg, "-vb"))
                {
                    m_VBdotNET = true;
                }
                else if (Insensitive.Equals(arg, "-usehrt"))
                {
                    m_UseHRT = true;
                }
            }

            try
            {
                if (m_Service)
                {
                    if (!Directory.Exists("Logs"))
                    {
                        Directory.CreateDirectory("Logs");
                    }

                    Console.SetOut(m_MultiConOut = new MultiTextWriter(new FileLogger("Logs/Console.log")));
                }
                else
                {
                    Console.SetOut(m_MultiConOut = new MultiTextWriter(Console.Out));
                }
            }
            catch
            { }

            m_Thread   = Thread.CurrentThread;
            m_Process  = Process.GetCurrentProcess();
            m_Assembly = Assembly.GetEntryAssembly();

            if (m_Thread != null)
            {
                m_Thread.Name = "Core Thread";
            }

            if (BaseDirectory.Length > 0)
            {
                Directory.SetCurrentDirectory(BaseDirectory);
            }

            var ttObj = new Timer.TimerThread();

            timerThread = new Thread(ttObj.TimerMain)
            {
                Name = "Timer Thread"
            };

            Version ver = m_Assembly.GetName().Version;

            String publishNumber = String.Empty;

            if (File.Exists("publish.txt"))
            {
                try
                {
                    publishNumber = File.ReadAllText("publish.txt", Encoding.UTF8);
                }
                catch
                { }
            }

            // Added to help future code support on forums, as a 'check' people can ask for to it see if they recompiled core or not
            Utility.PushColor(ConsoleColor.DarkGreen);
            Console.WriteLine(@"----------------------------------------------------------------------------");
            Utility.PopColor();
            Utility.PushColor(ConsoleColor.Cyan);
            Console.WriteLine("JustUO - [http://www.playuo.org] Version {0}.{1}", ver.Major, ver.Minor);

            if (!String.IsNullOrWhiteSpace(publishNumber))
            {
                Console.WriteLine("Publish {0}", publishNumber);
            }

            Utility.PopColor();

            Console.WriteLine(
                "Core: .NET Framework Version {0}.{1}.{2}",
                Environment.Version.Major,
                Environment.Version.Minor,
                Environment.Version.Build);

            string s = Arguments;

            if (s.Length > 0)
            {
                Utility.PushColor(ConsoleColor.Yellow);
                Console.WriteLine("Core: Running with arguments: {0}", s);
                Utility.PopColor();
            }

            m_ProcessorCount = Environment.ProcessorCount;

            if (m_ProcessorCount > 1)
            {
                m_MultiProcessor = true;
            }

            if (m_MultiProcessor || Is64Bit)
            {
                Utility.PushColor(ConsoleColor.Green);
                Console.WriteLine(
                    "Core: Optimizing for {0} {2}processor{1}",
                    m_ProcessorCount,
                    m_ProcessorCount == 1 ? "" : "s",
                    Is64Bit ? "64-bit " : "");
                Utility.PopColor();
            }

            var platform = (int)Environment.OSVersion.Platform;

            if (platform == 4 || platform == 128)
            {
                // MS 4, MONO 128
                m_Unix = true;
                Utility.PushColor(ConsoleColor.Yellow);
                Console.WriteLine("Core: Unix environment detected");
                Utility.PopColor();
            }
            else
            {
                m_ConsoleEventHandler = OnConsoleEvent;
                UnsafeNativeMethods.SetConsoleCtrlHandler(m_ConsoleEventHandler, true);
            }

            if (GCSettings.IsServerGC)
            {
                Utility.PushColor(ConsoleColor.DarkYellow);
                Console.WriteLine("Core: Server garbage collection mode enabled");
                Utility.PopColor();
            }

            if (m_UseHRT)
            {
                Console.WriteLine(
                    "Core: Requested high resolution timing ({0})", UsingHighResolutionTiming ? "Supported" : "Unsupported");
            }

            Console.WriteLine("RandomImpl: {0} ({1})", RandomImpl.Type.Name, RandomImpl.IsHardwareRNG ? "Hardware" : "Software");

            _OpenUOSDK = new OpenUOSDK();

            while (!ScriptCompiler.Compile(m_Debug, m_Cache))
            {
                Utility.PushColor(ConsoleColor.Red);
                Console.WriteLine("Scripts: One or more scripts failed to compile or no script files were found.");
                Utility.PopColor();

                if (m_Service)
                {
                    return;
                }

                Console.WriteLine(" - Press return to exit, or R to try again.");

                if (Console.ReadKey(true).Key != ConsoleKey.R)
                {
                    return;
                }
            }

            ScriptCompiler.Invoke("Configure");

            Region.Load();
            World.Load();

            ScriptCompiler.Invoke("Initialize");

            MessagePump messagePump = m_MessagePump = new MessagePump();

            timerThread.Start();

            foreach (Map m in Map.AllMaps)
            {
                m.Tiles.Force();
            }

            NetState.Initialize();

            EventSink.InvokeServerStarted();

            try
            {
                long now, last = TickCount;

                const int   sampleInterval = 100;
                const float ticksPerSecond = (float)(1000 * sampleInterval);

                long sample = 0;

                while (!m_Closing)
                {
                    m_Signal.WaitOne();

                    Mobile.ProcessDeltaQueue();
                    Item.ProcessDeltaQueue();

                    Timer.Slice();
                    messagePump.Slice();

                    NetState.FlushAll();
                    NetState.ProcessDisposedQueue();

                    if (Slice != null)
                    {
                        Slice();
                    }

                    if ((++sample % sampleInterval) == 0)
                    {
                        now = TickCount;
                        m_CyclesPerSecond[m_CycleIndex++ % m_CyclesPerSecond.Length] = ticksPerSecond / (now - last);
                        last = now;
                    }
                }
            }
            catch (Exception e)
            {
                CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, true));
            }
        }
コード例 #30
0
 public static extern bool SetConsoleCtrlHandler(ConsoleEventHandler handler, bool add);
コード例 #31
0
ファイル: Main.cs プロジェクト: walshie1986/runuot2a
        public static void Main(string[] args)
        {
            bool isService = !Insensitive.Equals(System.IO.Directory.GetCurrentDirectory().TrimEnd('\\'), System.AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\'));

            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            AppDomain.CurrentDomain.ProcessExit        += new EventHandler(CurrentDomain_ProcessExit);

            for (int i = 0; i < args.Length; ++i)
            {
                if (Insensitive.Equals(args[i], "-debug"))
                {
                    m_Debug = true;
                }
                else if (Insensitive.Equals(args[i], "-service"))
                {
                    m_Service = true;
                }
                else if (Insensitive.Equals(args[i], "-profile"))
                {
                    Profiling = true;
                }
                else if (Insensitive.Equals(args[i], "-nocache"))
                {
                    m_Cache = false;
                }
                else if (Insensitive.Equals(args[i], "-haltonwarning"))
                {
                    m_HaltOnWarning = true;
                }
                else if (Insensitive.Equals(args[i], "-vb"))
                {
                    m_VBdotNET = true;
                }
            }
            Console.WriteLine("{0}, {1}, {2}", System.IO.Directory.GetCurrentDirectory(), System.AppDomain.CurrentDomain.BaseDirectory, isService);
            System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory);
#if !MONO
            if (isService)
            {
                ServiceMain();
                return;
            }
#endif

            try
            {
                if (m_Service)
                {
                    if (!Directory.Exists("Logs"))
                    {
                        Directory.CreateDirectory("Logs");
                    }

                    Console.SetOut(m_MultiConOut = new MultiTextWriter(Console.Out, new FileLogger("Logs/" + DateTime.Now.ToString("yyyy-MM-dd.HH-mm-ss") + ".log")));
                }
                else
                {
                    Console.SetOut(m_MultiConOut = new MultiTextWriter(Console.Out));
                }
            }
            catch
            {
            }

            m_Thread   = Thread.CurrentThread;
            m_Process  = Process.GetCurrentProcess();
            m_Assembly = Assembly.GetEntryAssembly();

            if (m_Thread != null)
            {
                m_Thread.Name = "Core Thread";
            }

            if (BaseDirectory.Length > 0)
            {
                Directory.SetCurrentDirectory(BaseDirectory);
            }

            Timer.TimerThread ttObj = new Timer.TimerThread();
            timerThread      = new Thread(new ThreadStart(ttObj.TimerMain));
            timerThread.Name = "Timer Thread";

            Version ver = m_Assembly.GetName().Version;

            // Added to help future code support on forums, as a 'check' people can ask for to it see if they recompiled core or not
            Console.WriteLine("RunUO - [www.runuo.com] Version {0}.{1}, Build {2}.{3}", ver.Major, ver.Minor, ver.Build, ver.Revision);
            Console.WriteLine("Core: Running on .NET Framework Version {0}.{1}.{2}", Environment.Version.Major, Environment.Version.Minor, Environment.Version.Build);

            string s = Arguments;

            if (args.Length > 0)
            {
                Console.WriteLine("Core: Running with arguments: {0}", args);
            }

            m_ProcessorCount = Environment.ProcessorCount;

            if (m_ProcessorCount > 1)
            {
                m_MultiProcessor = true;
            }

            if (m_MultiProcessor || Is64Bit)
            {
                Console.WriteLine("Core: Optimizing for {0} {2}processor{1}", m_ProcessorCount, m_ProcessorCount == 1 ? "" : "s", Is64Bit ? "64-bit " : "");
            }

            int platform = (int)Environment.OSVersion.Platform;
            if ((platform == 4) || (platform == 128))                     // MS 4, MONO 128
            {
                m_Unix = true;
                Console.WriteLine("Core: Unix environment detected");
            }
            else
            {
                m_ConsoleEventHandler = new ConsoleEventHandler(OnConsoleEvent);
                SetConsoleCtrlHandler(m_ConsoleEventHandler, true);
            }

            while (!ScriptCompiler.Compile(m_Debug, m_Cache))
            {
                Console.WriteLine("Scripts: One or more scripts failed to compile or no script files were found.");
                Console.WriteLine(" - Press return to exit, or R to try again.");

                if (Console.ReadKey(true).Key != ConsoleKey.R)
                {
                    return;
                }
            }

            SocketPool.Create();

            MessagePump ms = m_MessagePump = new MessagePump();

            timerThread.Start();

            for (int i = 0; i < Map.AllMaps.Count; ++i)
            {
                Map.AllMaps[i].Tiles.Force();
            }

            NetState.Initialize();

            EventSink.InvokeServerStarted();

            try
            {
                DateTime now, last = DateTime.Now;

                const int   sampleInterval = 100;
                const float ticksPerSecond = (float)(TimeSpan.TicksPerSecond * sampleInterval);

                int sample = 0;

                while (!m_Closing && m_Signal.WaitOne())
                {
                    Mobile.ProcessDeltaQueue();
                    Item.ProcessDeltaQueue();

                    Timer.Slice();
                    m_MessagePump.Slice();

                    NetState.FlushAll();
                    NetState.ProcessDisposedQueue();

                    if (Slice != null)
                    {
                        Slice();
                    }

                    if ((++sample % sampleInterval) == 0)
                    {
                        now = DateTime.Now;
                        m_CyclesPerSecond[m_CycleIndex++ % m_CyclesPerSecond.Length] =
                            ticksPerSecond / (now.Ticks - last.Ticks);
                        last = now;
                    }
                }
            }
#if !MONO
            catch (ThreadAbortException e)
            {
                e.GetBaseException();                 //Just to remove warning. I can't remember how to supress...
                Thread.ResetAbort();
                HandleClosed();
                //Kill(false);
            }
#endif
            catch (Exception e)
            {
                CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, true));
            }
        }
コード例 #32
0
ファイル: Main.cs プロジェクト: greeduomacro/hubroot
		public static void Main( string[] args )
		{
			AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler( CurrentDomain_UnhandledException );
			AppDomain.CurrentDomain.ProcessExit += new EventHandler( CurrentDomain_ProcessExit );

            Console.BackgroundColor = ConsoleColor.Black;
            Console.ForegroundColor = ConsoleColor.Gray;

			Console.Title = "UO Aberration : Core";

			for( int i = 0; i < args.Length; ++i )
			{
				if( Insensitive.Equals( args[i], "-debug" ) )
					m_Debug = true;
				else if( Insensitive.Equals( args[i], "-service" ) )
					m_Service = true;
				else if( Insensitive.Equals( args[i], "-profile" ) )
					Profiling = true;
				else if( Insensitive.Equals( args[i], "-nocache" ) )
					m_Cache = false;
				else if( Insensitive.Equals( args[i], "-haltonwarning" ) )
					m_HaltOnWarning = true;
			}

			try
			{
				if( m_Service )
				{
					if( !Directory.Exists( "Logs" ) )
						Directory.CreateDirectory( "Logs" );

					Console.SetOut( m_MultiConOut = new MultiTextWriter( new FileLogger( "Logs/Console.log" ) ) );
				}

				else
				{
					Console.SetOut( m_MultiConOut = new MultiTextWriter( Console.Out ) );
				}
			}

			catch			{			}

			m_Thread = Thread.CurrentThread;
			m_Process = Process.GetCurrentProcess();
			m_Assembly = Assembly.GetEntryAssembly();

			if( m_Thread != null )
				m_Thread.Name = "Core Thread";

			if( BaseDirectory.Length > 0 )
				Directory.SetCurrentDirectory( BaseDirectory );

			Timer.TimerThread ttObj = new Timer.TimerThread();
			timerThread = new Thread( new ThreadStart( ttObj.TimerMain ) );
			timerThread.Name = "Timer Thread";

			Version ver = m_Assembly.GetName().Version;

            /*
             * ServUO's Original Code
            if (File.Exists("publish.txt"))
            {
                try
                {
                    FileStream fs = new FileStream("publish.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
                    StreamReader sr = new StreamReader(fs);

                    publishNumber = sr.ReadLine();

                    sr.Close();
                    fs.Close();
                }
                catch
                { }
            }*/
            //Concept Expanded based upon ServUO's publish number.

            string header = "";
            ConsoleColor desiredColor = ConsoleColor.White;

            if (File.Exists("header.txt"))
            {
                bool chopColor = false;

                try
                {
                    FileStream file = new FileStream("header.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
                    StreamReader reader = new StreamReader(file);

                    string determineTextColor = (string)(reader.ReadLine().Trim().ToLower());

                    if (Enum.TryParse<ConsoleColor>(determineTextColor, true, out desiredColor))
                        chopColor = true;

                    else Utility.PushColor(ConsoleColor.White);

                    if (chopColor)
                    {
                        header = (string)(reader.ReadToEnd());
                    }

                    file.Close();
                    reader.Close();

                    file.Dispose();
                    reader.Dispose();
                }

                catch
                {
                    Utility.PushColor(ConsoleColor.Red);
                    Console.Write("Error: ");
                    Utility.PushColor(ConsoleColor.White);
                    Console.WriteLine("Your are either missing header.txt or it is misconfigured.");
                }
            }

            else 
            {
                Utility.PushColor(ConsoleColor.Red);
                Console.Write("Error: ");
                Utility.PushColor(ConsoleColor.White);
                Console.WriteLine("header.txt could not be located.");
            }

            Utility.PushColor( desiredColor );
            Console.WriteLine( header );
            Utility.PushColor(ConsoleColor.White);
            Console.WriteLine();
			Console.WriteLine( "Core ({3}): Running on .NET Framework Version {0}.{1}.{2}", Environment.Version.Major, Environment.Version.Minor, Environment.Version.Build, Environment.Is64BitProcess ? "x64" : "x86" );

			string s = Arguments;

			if( s.Length > 0 )
				Console.WriteLine( "Core: Running with arguments: {0}", s );

			m_ProcessorCount = Environment.ProcessorCount;

			if( m_ProcessorCount > 1 )
				m_MultiProcessor = true;

			if( m_MultiProcessor || Is64Bit )
				Console.WriteLine( "Core: Optimizing for {0} {2}processor{1}", m_ProcessorCount, m_ProcessorCount == 1 ? "" : "s", Is64Bit ? "64-bit " : "" );

			int platform = (int)Environment.OSVersion.Platform;
			if( platform == 4 || platform == 128 ) { // MS 4, MONO 128
				m_Unix = true;
				Console.WriteLine( "Core: Unix environment detected" );
			}
			else {
				m_ConsoleEventHandler = new ConsoleEventHandler( OnConsoleEvent );
				SetConsoleCtrlHandler( m_ConsoleEventHandler, true );
			}

			if( GCSettings.IsServerGC )
				Console.WriteLine( "Core: Server garbage collection mode enabled" );

			while( !ScriptCompiler.Compile( m_Debug, m_Cache ) )
			{
				Console.WriteLine( "Scripts: One or more scripts failed to compile or no script files were found." );

				if( m_Service )
					return;

				Console.WriteLine( " - Press return to exit, or R to try again." );

				if( Console.ReadKey( true ).Key != ConsoleKey.R )
					return;
			}

			ScriptCompiler.Invoke( "Configure" );

			Region.Load();
			World.Load();

			ScriptCompiler.Invoke( "Initialize" );

			MessagePump messagePump = m_MessagePump = new MessagePump();

			timerThread.Start();

			for( int i = 0; i < Map.AllMaps.Count; ++i )
				Map.AllMaps[i].Tiles.Force();

			NetState.Initialize();

			EventSink.InvokeServerStarted();

			try
			{
				DateTime now, last = DateTime.UtcNow;

				const int sampleInterval = 100;
				const float ticksPerSecond = (float)(TimeSpan.TicksPerSecond * sampleInterval);

				long sample = 0;

				while( m_Signal.WaitOne() )
				{
					Mobile.ProcessDeltaQueue();
					Item.ProcessDeltaQueue();

					Timer.Slice();
					messagePump.Slice();

					NetState.FlushAll();
					NetState.ProcessDisposedQueue();

					if( Slice != null )
						Slice();

					if( (++sample % sampleInterval) == 0 )
					{
						now = DateTime.UtcNow;
						m_CyclesPerSecond[m_CycleIndex++ % m_CyclesPerSecond.Length] =
							ticksPerSecond / (now.Ticks - last.Ticks);
						last = now;
					}
				}
			}
			catch( Exception e )
			{
				CurrentDomain_UnhandledException( null, new UnhandledExceptionEventArgs( e, true ) );
			}
		}
コード例 #33
0
ファイル: Main.cs プロジェクト: BackupTheBerlios/sunuo-svn
        public static void Main( string[] args )
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler( CurrentDomain_UnhandledException );
            AppDomain.CurrentDomain.ProcessExit += new EventHandler( CurrentDomain_ProcessExit );

            bool debug = false;

            for ( int i = 0; i < args.Length; ++i )
            {
                if ( Insensitive.Equals( args[i], "-debug" ) )
                    debug = true;
                else if ( Insensitive.Equals( args[i], "-service" ) )
                    m_Service = true;
                else if ( Insensitive.Equals( args[i], "-profile" ) )
                    Profiling = true;
            }

            try
            {
                if ( m_Service )
                {
                    if ( !Directory.Exists( "Logs" ) )
                        Directory.CreateDirectory( "Logs" );

                    Console.SetOut( m_MultiConOut = new MultiTextWriter( Console.Out, new FileLogger( "Logs/Console.log" ) ) );
                }
                else
                {
                    Console.SetOut(  m_MultiConOut = new MultiTextWriter( Console.Out ) );
                }
            }
            catch
            {
            }

            #if !MONO
            m_ConsoleEventHandler = new ConsoleEventHandler( OnConsoleEvent );
            SetConsoleCtrlHandler( m_ConsoleEventHandler, true );
            #endif

            m_Thread = Thread.CurrentThread;
            m_Process = Process.GetCurrentProcess();
            m_Assembly = Assembly.GetEntryAssembly();

            if ( m_Thread != null )
                m_Thread.Name = "Core Thread";

            if ( BaseDirectory.Length > 0 )
                Directory.SetCurrentDirectory( BaseDirectory );

            Timer.TimerThread ttObj = new Timer.TimerThread();
            timerThread = new Thread( new ThreadStart( ttObj.TimerMain ) );
            timerThread.Name = "Timer Thread";

            Version ver = m_Assembly.GetName().Version;

            // Added to help future code support on forums, as a 'check' people can ask for to it see if they recompiled core or not
            Console.WriteLine( "RunUO - [www.runuo.com] Version {0}.{1}.{3}, Build {2}", ver.Major, ver.Minor, ver.Revision, ver.Build );

            while ( !ScriptCompiler.Compile( debug ) )
            {
                Console.WriteLine( "Scripts: One or more scripts failed to compile or no script files were found." );
                Console.WriteLine( " - Press return to exit, or R to try again." );

                string line = Console.ReadLine();
                if ( line == null || line.ToLower() != "r" )
                    return;
            }

            Region.Load();

            MessagePump ms = m_MessagePump = new MessagePump( new Listener( Listener.Port ) );

            timerThread.Start();

            for ( int i = 0; i < Map.AllMaps.Count; ++i )
                ((Map)Map.AllMaps[i]).Tiles.Force();

            NetState.Initialize();

            EventSink.InvokeServerStarted();

            try
            {
                while ( !m_Closing )
                {
                    Thread.Sleep( 1 );

                    Mobile.ProcessDeltaQueue();
                    Item.ProcessDeltaQueue();

                    Timer.Slice();
                    m_MessagePump.Slice();

                    NetState.FlushAll();
                    NetState.ProcessDisposedQueue();

                    if ( Slice != null )
                        Slice();
                }
            }
            catch ( Exception e )
            {
                CurrentDomain_UnhandledException( null, new UnhandledExceptionEventArgs( e, true ) );
            }

            if ( timerThread.IsAlive )
                timerThread.Abort();
        }
コード例 #34
0
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            AppDomain.CurrentDomain.ProcessExit        += new EventHandler(CurrentDomain_ProcessExit);

            for (int i = 0; i < args.Length; ++i)
            {
                if (Insensitive.Equals(args[i], "-debug"))
                {
                    m_Debug = true;
                }
                else if (Insensitive.Equals(args[i], "-service"))
                {
                    m_Service = true;
                }
                else if (Insensitive.Equals(args[i], "-profile"))
                {
                    Profiling = true;
                }
                else if (Insensitive.Equals(args[i], "-nocache"))
                {
                    m_Cache = false;
                }
                else if (Insensitive.Equals(args[i], "-haltonwarning"))
                {
                    m_HaltOnWarning = true;
                }
                else if (Insensitive.Equals(args[i], "-vb"))
                {
                    m_VBdotNET = true;
                }
            }

            try
            {
                if (m_Service)
                {
                    if (!Directory.Exists("Logs"))
                    {
                        Directory.CreateDirectory("Logs");
                    }

                    Console.SetOut(m_MultiConOut = new MultiTextWriter(new FileLogger("Logs/Console.log")));
                }
                else
                {
                    Console.SetOut(m_MultiConOut = new MultiTextWriter(Console.Out));
                }
            }
            catch
            {
            }

            m_Thread   = Thread.CurrentThread;
            m_Process  = Process.GetCurrentProcess();
            m_Assembly = Assembly.GetEntryAssembly();

            if (m_Thread != null)
            {
                m_Thread.Name = "Core Thread";
            }

            if (BaseDirectory.Length > 0)
            {
                Directory.SetCurrentDirectory(BaseDirectory);
            }

            Timer.TimerThread ttObj = new Timer.TimerThread();
            timerThread      = new Thread(new ThreadStart(ttObj.TimerMain));
            timerThread.Name = "Timer Thread";

            Version ver = m_Assembly.GetName().Version;

            String publishNumber = "";

            if (File.Exists("publish.txt"))
            {
                try
                {
                    FileStream   fs = new FileStream("publish.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
                    StreamReader sr = new StreamReader(fs);

                    publishNumber = sr.ReadLine();

                    sr.Close();
                    fs.Close();
                }
                catch { }
            }

            // Added to help future code support on forums, as a 'check' people can ask for to it see if they recompiled core or not
            Utility.PushColor(ConsoleColor.DarkGreen);
            Console.WriteLine(@"----------------------------------------------------------------------------");
            Utility.PopColor();
            Utility.PushColor(ConsoleColor.Cyan);
            Console.WriteLine("ServUO - [http://www.servuo.com] Version {0}.{1}, Build {2}.{3}", ver.Major, ver.Minor, ver.Build, ver.Revision);
            Console.WriteLine("Publish {0}", publishNumber);
            Utility.PopColor();

            string s = Arguments;

            if (s.Length > 0)
            {
                Utility.PushColor(ConsoleColor.Yellow);
                Console.WriteLine("Core: Running with arguments: {0}", s);
                Utility.PopColor();
            }

            m_ProcessorCount = Environment.ProcessorCount;

            if (m_ProcessorCount > 1)
            {
                m_MultiProcessor = true;
            }

            if (m_MultiProcessor || Is64Bit)
            {
                Utility.PushColor(ConsoleColor.Green);
                Console.WriteLine("Core: Optimizing for {0} {2}processor{1}", m_ProcessorCount, m_ProcessorCount == 1 ? "" : "s", Is64Bit ? "64-bit " : "");
                Utility.PopColor();
            }

            int platform = (int)Environment.OSVersion.Platform;

            if (platform == 4 || platform == 128)
            {             // MS 4, MONO 128
                m_Unix = true;
                Utility.PushColor(ConsoleColor.Yellow);
                Console.WriteLine("Core: Unix environment detected");
                Utility.PopColor();
            }
            else
            {
                m_ConsoleEventHandler = new ConsoleEventHandler(OnConsoleEvent);
                SetConsoleCtrlHandler(m_ConsoleEventHandler, true);
            }

            if (GCSettings.IsServerGC)
            {
                Utility.PushColor(ConsoleColor.DarkYellow);
                Console.WriteLine("Core: Server garbage collection mode enabled");
                Utility.PopColor();
            }

            _openUOSDK = new OpenUOSDK();

            while (!ScriptCompiler.Compile(m_Debug, m_Cache))
            {
                Utility.PushColor(ConsoleColor.Red);
                Console.WriteLine("Scripts: One or more scripts failed to compile or no script files were found.");
                Utility.PopColor();

                if (m_Service)
                {
                    return;
                }

                Console.WriteLine(" - Press return to exit, or R to try again.");

                if (Console.ReadKey(true).Key != ConsoleKey.R)
                {
                    return;
                }
            }

            ScriptCompiler.Invoke("Configure");

            Region.Load();
            World.Load();

            ScriptCompiler.Invoke("Initialize");

            MessagePump messagePump = new MessagePump();

            timerThread.Start();

            for (int i = 0; i < Map.AllMaps.Count; ++i)
            {
                Map.AllMaps[i].Tiles.Force();
            }

            NetState.Initialize();

            EventSink.InvokeServerStarted();

            try
            {
                DateTime now, last = DateTime.UtcNow;

                const int   sampleInterval = 100;
                const float ticksPerSecond = (float)(TimeSpan.TicksPerSecond * sampleInterval);

                long sample = 0;

                while (m_Signal.WaitOne())
                {
                    Mobile.ProcessDeltaQueue();
                    Item.ProcessDeltaQueue();

                    Timer.Slice();
                    messagePump.Slice();

                    NetState.FlushAll();
                    NetState.ProcessDisposedQueue();

                    if (Slice != null)
                    {
                        Slice();
                    }

                    if ((++sample % sampleInterval) == 0)
                    {
                        now = DateTime.UtcNow;
                        m_CyclesPerSecond[m_CycleIndex++ % m_CyclesPerSecond.Length] =
                            ticksPerSecond / (now.Ticks - last.Ticks);
                        last = now;
                    }
                }
            }
            catch (Exception e)
            {
                CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, true));
            }
        }
コード例 #35
0
        public static string ReadLine(string input = "", ConsoleEventHandler onTab = null)
        {
            int startLeft = System.Console.CursorLeft;
            int startTop  = System.Console.CursorTop;

            int relativeLeft = input.Length;

            while (true)
            {
                RedrawConsoleInput(input, startLeft, startTop);

                //System.Console.CursorLeft = startLeft + relativeLeft;

                int trl = startLeft + relativeLeft;
                System.Console.CursorLeft = trl % System.Console.WindowWidth;
                System.Console.CursorTop  = trl / System.Console.WindowWidth + startTop;

                System.Console.CursorVisible = true;
                var key = System.Console.ReadKey(true);
                System.Console.CursorVisible = false;
                if (key.Key == ConsoleKey.Enter)
                {
                    return(input);
                }
                else if (key.Key == ConsoleKey.Tab)
                {
                    if (onTab != null)
                    {
                        ConsoleEventArgs e = new ConsoleEventArgs(relativeLeft, input);
                        onTab(null, e);
                        if (e.Update)
                        {
                            relativeLeft = e.CursorLeft;
                            input        = e.Input;
                        }
                    }
                }
                else if (key.Key == ConsoleKey.LeftArrow)
                {
                    if (relativeLeft > 0)
                    {
                        relativeLeft--;
                    }
                }
                else if (key.Key == ConsoleKey.RightArrow)
                {
                    if (relativeLeft < input.Length)
                    {
                        relativeLeft++;
                    }
                }
                else if (key.Key == ConsoleKey.Backspace)
                {
                    if (relativeLeft > 0)
                    {
                        relativeLeft--;
                        input = input.Remove(relativeLeft, 1);
                        RedrawConsoleInput(input, startLeft, startTop);
                    }
                }
                else if (key.Key == ConsoleKey.Delete)
                {
                    if (relativeLeft < input.Length)
                    {
                        input = input.Remove(relativeLeft, 1);
                        RedrawConsoleInput(input, startLeft, startTop);
                    }
                }
                else if (key.Key == ConsoleKey.Insert)
                {
                    // Can't enable insert mode.
                }
                else if (key.Key == ConsoleKey.End)
                {
                    relativeLeft = input.Length;
                }
                else if (key.Key == ConsoleKey.Home)
                {
                    relativeLeft = 0;
                }
                else
                {
                    if (key.KeyChar != '\0')
                    {
                        input = input.Insert(relativeLeft, key.KeyChar.ToString());
                        RedrawConsoleInput(input, startLeft, startTop);
                        relativeLeft++;
                    }
                }
            }
        }
コード例 #36
0
ファイル: Main.cs プロジェクト: Delphi79/RunUO-2.4
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            AppDomain.CurrentDomain.ProcessExit        += new EventHandler(CurrentDomain_ProcessExit);

            for (int i = 0; i < args.Length; ++i)
            {
                if (Insensitive.Equals(args[i], "-debug"))
                {
                    m_Debug = true;
                }
                else if (Insensitive.Equals(args[i], "-service"))
                {
                    m_Service = true;
                }
                else if (Insensitive.Equals(args[i], "-profile"))
                {
                    Profiling = true;
                }
                else if (Insensitive.Equals(args[i], "-nocache"))
                {
                    m_Cache = false;
                }
                else if (Insensitive.Equals(args[i], "-haltonwarning"))
                {
                    m_HaltOnWarning = true;
                }
                else if (Insensitive.Equals(args[i], "-vb"))
                {
                    m_VBdotNET = true;
                }
            }

            try
            {
                if (m_Service)
                {
                    if (!Directory.Exists("Logs"))
                    {
                        Directory.CreateDirectory("Logs");
                    }

                    Console.SetOut(m_MultiConOut = new MultiTextWriter(new FileLogger("Logs/Console.log")));
                }
                else
                {
                    Console.SetOut(m_MultiConOut = new MultiTextWriter(Console.Out));
                }
            }
            catch
            {
            }

            m_Thread   = Thread.CurrentThread;
            m_Process  = Process.GetCurrentProcess();
            m_Assembly = Assembly.GetEntryAssembly();

            if (m_Thread != null)
            {
                m_Thread.Name = "Core Thread";
            }

            if (BaseDirectory.Length > 0)
            {
                Directory.SetCurrentDirectory(BaseDirectory);
            }

            Timer.TimerThread ttObj = new Timer.TimerThread();
            timerThread      = new Thread(new ThreadStart(ttObj.TimerMain));
            timerThread.Name = "Timer Thread";

            Version ver = m_Assembly.GetName().Version;

            // Added to help future code support on forums, as a 'check' people can ask for to it see if they recompiled core or not
            Console.WriteLine("RunUO - [www.runuo.com] Version {0}.{1}, Build {2}.{3}", ver.Major, ver.Minor, ver.Build, ver.Revision);
            Console.WriteLine("Core: Running on .NET Framework Version {0}.{1}.{2}", Environment.Version.Major, Environment.Version.Minor, Environment.Version.Build);

            string s = Arguments;

            if (s.Length > 0)
            {
                Console.WriteLine("Core: Running with arguments: {0}", s);
            }

            m_ProcessorCount = Environment.ProcessorCount;

            if (m_ProcessorCount > 1)
            {
                m_MultiProcessor = true;
            }

            if (m_MultiProcessor || Is64Bit)
            {
                Console.WriteLine("Core: Optimizing for {0} {2}processor{1}", m_ProcessorCount, m_ProcessorCount == 1 ? "" : "s", Is64Bit ? "64-bit " : "");
            }

            int platform = (int)Environment.OSVersion.Platform;

            if (platform == 4 || platform == 128)                // MS 4, MONO 128
            {
                m_Unix = true;
                Console.WriteLine("Core: Unix environment detected");
            }
            else
            {
                m_ConsoleEventHandler = new ConsoleEventHandler(OnConsoleEvent);
                UnsafeNativeMethods.SetConsoleCtrlHandler(m_ConsoleEventHandler, true);
            }

            if (GCSettings.IsServerGC)
            {
                Console.WriteLine("Core: Server garbage collection mode enabled");
            }

            Console.WriteLine("RandomImpl: {0} ({1})", RandomImpl.Type.Name, RandomImpl.IsHardwareRNG ? "Hardware" : "Software");

            while (!ScriptCompiler.Compile(m_Debug, m_Cache))
            {
                Console.WriteLine("Scripts: One or more scripts failed to compile or no script files were found.");

                if (m_Service)
                {
                    return;
                }

                Console.WriteLine(" - Press return to exit, or R to try again.");

                if (Console.ReadKey(true).Key != ConsoleKey.R)
                {
                    return;
                }
            }

            ScriptCompiler.Invoke("Configure");

            Region.Load();
            World.Load();

            ScriptCompiler.Invoke("Initialize");

            MessagePump messagePump = m_MessagePump = new MessagePump();

            timerThread.Start();

            for (int i = 0; i < Map.AllMaps.Count; ++i)
            {
                Map.AllMaps[i].Tiles.Force();
            }

            NetState.Initialize();

            EventSink.InvokeServerStarted();

            try
            {
                long now, last = TickCount;

                const int   sampleInterval = 100;
                const float ticksPerSecond = (float)(1000 * sampleInterval);

                long sample = 0;

                while (!m_Closing)
                {
                    m_Signal.WaitOne();

                    Mobile.ProcessDeltaQueue();
                    Item.ProcessDeltaQueue();

                    Timer.Slice();
                    messagePump.Slice();

                    NetState.FlushAll();
                    NetState.ProcessDisposedQueue();

                    if (Slice != null)
                    {
                        Slice();
                    }

                    if ((++sample % sampleInterval) == 0)
                    {
                        now = TickCount;
                        m_CyclesPerSecond[m_CycleIndex++ % m_CyclesPerSecond.Length] =
                            ticksPerSecond / (now - last);
                        last = now;
                    }
                }
            }
            catch (Exception e)
            {
                CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, true));
            }
        }
コード例 #37
0
 private static void HookupConsoleHandler()
 {
     _consoleHandler += new ConsoleEventHandler(ConsoleHandler);
     SetConsoleCtrlHandler(_consoleHandler, true);
 }
コード例 #38
0
ファイル: Main.cs プロジェクト: mikkelhartmann/ServUO
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            AppDomain.CurrentDomain.ProcessExit        += CurrentDomain_ProcessExit;

            foreach (string a in args)
            {
                if (Insensitive.Equals(a, "-debug"))
                {
                    Debug = true;
                }
                else if (Insensitive.Equals(a, "-service"))
                {
                    Service = true;
                }
                else if (Insensitive.Equals(a, "-profile"))
                {
                    Profiling = true;
                }
                else if (Insensitive.Equals(a, "-nocache"))
                {
                    _Cache = false;
                }
                else if (Insensitive.Equals(a, "-haltonwarning"))
                {
                    HaltOnWarning = true;
                }
                else if (Insensitive.Equals(a, "-vb"))
                {
                    VBdotNet = true;
                }
                else if (Insensitive.Equals(a, "-usehrt"))
                {
                    _UseHRT = true;
                }
            }

            try
            {
                if (Service)
                {
                    if (!Directory.Exists("Logs"))
                    {
                        Directory.CreateDirectory("Logs");
                    }

                    Console.SetOut(MultiConsoleOut = new MultiTextWriter(new FileLogger("Logs/Console.log")));
                }
                else
                {
                    Console.SetOut(MultiConsoleOut = new MultiTextWriter(Console.Out));
                }
            }
            catch
            { }

            Thread   = Thread.CurrentThread;
            Process  = Process.GetCurrentProcess();
            Assembly = Assembly.GetEntryAssembly();

            if (Thread != null)
            {
                Thread.Name = "Core Thread";
            }

            if (BaseDirectory.Length > 0)
            {
                Directory.SetCurrentDirectory(BaseDirectory);
            }

            Timer.TimerThread ttObj = new Timer.TimerThread();

            _TimerThread = new Thread(ttObj.TimerMain)
            {
                Name = "Timer Thread"
            };

            Version ver = Assembly.GetName().Version;

            // Added to help future code support on forums, as a 'check' people can ask for to it see if they recompiled core or not
            Utility.PushColor(ConsoleColor.DarkGreen);
            Console.WriteLine(new String('-', Console.BufferWidth));
            Utility.PopColor();
            Utility.PushColor(ConsoleColor.Cyan);
            Console.WriteLine(
                "ServUO - [http://www.servuo.com] Version {0}.{1}, Build {2}.{3}",
                ver.Major,
                ver.Minor,
                ver.Build,
                ver.Revision);
            Utility.PopColor();

            string s = Arguments;

            if (s.Length > 0)
            {
                Utility.PushColor(ConsoleColor.Yellow);
                Console.WriteLine("Core: Running with arguments: {0}", s);
                Utility.PopColor();
            }

            ProcessorCount = Environment.ProcessorCount;

            if (ProcessorCount > 1)
            {
                MultiProcessor = true;
            }

            if (MultiProcessor || Is64Bit)
            {
                Utility.PushColor(ConsoleColor.Green);
                Console.WriteLine(
                    "Core: Optimizing for {0} {2}processor{1}",
                    ProcessorCount,
                    ProcessorCount == 1 ? "" : "s",
                    Is64Bit ? "64-bit " : "");
                Utility.PopColor();
            }

            int platform = (int)Environment.OSVersion.Platform;

            if (platform == 4 || platform == 128)
            {
                // MS 4, MONO 128
                Unix = true;
                Utility.PushColor(ConsoleColor.Yellow);
                Console.WriteLine("Core: Unix environment detected");
                Utility.PopColor();
            }
            else
            {
                m_ConsoleEventHandler = OnConsoleEvent;
                UnsafeNativeMethods.SetConsoleCtrlHandler(m_ConsoleEventHandler, true);
            }

            if (GCSettings.IsServerGC)
            {
                Utility.PushColor(ConsoleColor.DarkYellow);
                Console.WriteLine("Core: Server garbage collection mode enabled");
                Utility.PopColor();
            }

            if (_UseHRT)
            {
                Utility.PushColor(ConsoleColor.DarkYellow);
                Console.WriteLine(
                    "Core: Requested high resolution timing ({0})",
                    UsingHighResolutionTiming ? "Supported" : "Unsupported");
                Utility.PopColor();
            }

            Utility.PushColor(ConsoleColor.DarkYellow);
            Console.WriteLine("RandomImpl: {0} ({1})", RandomImpl.Type.Name, RandomImpl.IsHardwareRNG ? "Hardware" : "Software");
            Utility.PopColor();

            Utility.PushColor(ConsoleColor.DarkYellow);
            Console.WriteLine("Core: Loading config...");
            Config.Load();
            Utility.PopColor();

            while (!ScriptCompiler.Compile(Debug, _Cache))
            {
                Utility.PushColor(ConsoleColor.Red);
                Console.WriteLine("Scripts: One or more scripts failed to compile or no script files were found.");
                Utility.PopColor();

                if (Service)
                {
                    return;
                }

                Console.WriteLine(" - Press return to exit, or R to try again.");

                if (Console.ReadKey(true).Key != ConsoleKey.R)
                {
                    return;
                }
            }

            ScriptCompiler.Invoke("Configure");

            Region.Load();
            World.Load();

            ScriptCompiler.Invoke("Initialize");

            MessagePump messagePump = MessagePump = new MessagePump();

            _TimerThread.Start();

            foreach (Map m in Map.AllMaps)
            {
                m.Tiles.Force();
            }

            NetState.Initialize();

            EventSink.InvokeServerStarted();

            try
            {
                long now, last = TickCount;

                const int   sampleInterval = 100;
                const float ticksPerSecond = 1000.0f * sampleInterval;

                long sample = 0;

                while (!Closing)
                {
                    _Signal.WaitOne();

                    Mobile.ProcessDeltaQueue();
                    Item.ProcessDeltaQueue();

                    Timer.Slice();
                    messagePump.Slice();

                    NetState.FlushAll();
                    NetState.ProcessDisposedQueue();

                    if (Slice != null)
                    {
                        Slice();
                    }

                    if (sample++ % sampleInterval != 0)
                    {
                        continue;
                    }

                    now = TickCount;
                    _CyclesPerSecond[_CycleIndex++ % _CyclesPerSecond.Length] = ticksPerSecond / (now - last);
                    last = now;
                }
            }
            catch (Exception e)
            {
                CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, true));
            }
        }
コード例 #39
0
        public static void Main(string[] args)
        {
#if !DEBUG
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
#endif
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);

            for (int i = 0; i < args.Length; ++i)
            {
                if (Insensitive.Equals(args[i], "-debug"))
                {
                    m_Debug = true;
                }
                else if (Insensitive.Equals(args[i], "-service"))
                {
                    m_Service = true;
                }
                else if (Insensitive.Equals(args[i], "-profile"))
                {
                    Profiling = true;
                }
                else if (Insensitive.Equals(args[i], "-nocache"))
                {
                    m_Cache = false;
                }
                else if (Insensitive.Equals(args[i], "-haltonwarning"))
                {
                    m_HaltOnWarning = true;
                }
                else if (Insensitive.Equals(args[i], "-vb"))
                {
                    m_VBdotNET = true;
                }
            }

            try
            {
                if (m_Service)
                {
                    if (!Directory.Exists("Logs"))
                    {
                        Directory.CreateDirectory("Logs");
                    }

                    Console.SetOut(m_MultiConOut = new MultiTextWriter(Console.Out, new FileLogger("Logs/Console.log")));
                }
                else
                {
                    Console.SetOut(m_MultiConOut = new MultiTextWriter(Console.Out));
                }
            }
            catch (Exception ex) { EventSink.InvokeLogException(new LogExceptionEventArgs(ex)); }

            m_Thread   = Thread.CurrentThread;
            m_Process  = Process.GetCurrentProcess();
            m_Assembly = Assembly.GetEntryAssembly();

            if (m_Thread != null)
            {
                m_Thread.Name = "Core Thread";
            }

            if (BaseDirectory.Length > 0)
            {
                Directory.SetCurrentDirectory(BaseDirectory);
            }

            Timer.TimerThread ttObj = new Timer.TimerThread();
            timerThread      = new Thread(new ThreadStart(ttObj.TimerMain));
            timerThread.Name = "Timer Thread";

            Version ver = m_Assembly.GetName().Version;

            // Added to help future code support on forums, as a 'check' people can ask for to it see if they recompiled core or not
            Console.WriteLine("Angel Island - [www.game-master.net] Version {0}.{1}.{3}, Build {2}", ver.Major, ver.Minor, ver.Revision, ver.Build);
#if DEBUG
            Console.WriteLine("[Debug Build Enabled]");
#endif
            string s = Arguments;

            if (s.Length > 0)
            {
                Console.WriteLine("Core: Running with arguments: {0}", s);
            }

            m_ProcessorCount = Environment.ProcessorCount;

            if (m_ProcessorCount > 1)
            {
                m_MultiProcessor = true;
            }

            if (m_MultiProcessor || Is64Bit)
            {
                Console.WriteLine("Core: Optimizing for {0} {2}processor{1}", m_ProcessorCount, m_ProcessorCount == 1 ? "" : "s", Is64Bit ? "64-bit " : "");
            }

            int platform = (int)Environment.OSVersion.Platform;
            if ((platform == 4) || (platform == 128))
            {             // MS 4, MONO 128
                m_Unix = true;
                Console.WriteLine("Core: Unix environment detected");
            }
            else
            {
                m_ConsoleEventHandler = new ConsoleEventHandler(OnConsoleEvent);
                SetConsoleCtrlHandler(m_ConsoleEventHandler, true);
            }

            while (!ScriptCompiler.Compile(m_Debug))
            {
                if (m_Quiet)                 //abort and exit if compile scripts failed
                {
                    return;
                }

                Console.WriteLine("Scripts: One or more scripts failed to compile or no script files were found.");
                Console.WriteLine(" - Press return to exit, or R to try again.");

                string line = Console.ReadLine();
                if (line == null || line.ToLower() != "r")
                {
                    return;
                }
            }

            // adam: I believe the new startup logic is nore robust as it attempts to prevents timers from firing
            //  before the shard is fully up and alive.

            Region.Load();

            SocketPool.Create();

            MessagePump ms = m_MessagePump = new MessagePump();

            timerThread.Start();

            for (int i = 0; i < Map.AllMaps.Count; ++i)
            {
                ((Map)Map.AllMaps[i]).Tiles.Force();
            }

            NetState.Initialize();

            EventSink.InvokeServerStarted();

#if !DEBUG
            try
            {
#endif
            while (m_Signal.WaitOne())
            {
                Mobile.ProcessDeltaQueue();
                Item.ProcessDeltaQueue();

                Timer.Slice();
                m_MessagePump.Slice();

                NetState.FlushAll();
                NetState.ProcessDisposedQueue();

                if (Slice != null)
                {
                    Slice();
                }
            }
#if !DEBUG
        }

        catch (Exception e)
        {
            CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, true));
        }
#endif
        }
コード例 #40
0
ファイル: Main.cs プロジェクト: rokann/JustUO
		public static void Main(string[] args)
		{
			AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
			AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;

			foreach (string arg in args)
			{
				if (Insensitive.Equals(arg, "-debug"))
				{
					m_Debug = true;
				}
				else if (Insensitive.Equals(arg, "-service"))
				{
					m_Service = true;
				}
				else if (Insensitive.Equals(arg, "-profile"))
				{
					Profiling = true;
				}
				else if (Insensitive.Equals(arg, "-nocache"))
				{
					m_Cache = false;
				}
				else if (Insensitive.Equals(arg, "-haltonwarning"))
				{
					m_HaltOnWarning = true;
				}
				else if (Insensitive.Equals(arg, "-vb"))
				{
					m_VBdotNET = true;
				}
				else if (Insensitive.Equals(arg, "-usehrt"))
				{
					m_UseHRT = true;
				}
			}

			try
			{
				if (m_Service)
				{
					if (!Directory.Exists("Logs"))
					{
						Directory.CreateDirectory("Logs");
					}

					Console.SetOut(m_MultiConOut = new MultiTextWriter(new FileLogger("Logs/Console.log")));
				}
				else
				{
					Console.SetOut(m_MultiConOut = new MultiTextWriter(Console.Out));
				}
			}
			catch
			{ }

			m_Thread = Thread.CurrentThread;
			m_Process = Process.GetCurrentProcess();
			m_Assembly = Assembly.GetEntryAssembly();

			if (m_Thread != null)
			{
				m_Thread.Name = "Core Thread";
			}

			if (BaseDirectory.Length > 0)
			{
				Directory.SetCurrentDirectory(BaseDirectory);
			}

			var ttObj = new Timer.TimerThread();

			timerThread = new Thread(ttObj.TimerMain)
			{
				Name = "Timer Thread"
			};

			Version ver = m_Assembly.GetName().Version;

			String publishNumber = String.Empty;

			if (File.Exists("publish.txt"))
			{
				try
				{
					publishNumber = File.ReadAllText("publish.txt", Encoding.UTF8);
				}
				catch
				{ }
			}

			// Added to help future code support on forums, as a 'check' people can ask for to it see if they recompiled core or not
			Utility.PushColor(ConsoleColor.DarkGreen);
			Console.WriteLine(@"----------------------------------------------------------------------------");
			Utility.PopColor();
			Utility.PushColor(ConsoleColor.Cyan);
			Console.WriteLine("JustUO - [http://www.playuo.org] Version {0}.{1}", ver.Major, ver.Minor);

			if (!String.IsNullOrWhiteSpace(publishNumber))
			{
				Console.WriteLine("Publish {0}", publishNumber);
			}

			Utility.PopColor();

			Console.WriteLine(
				"Core: .NET Framework Version {0}.{1}.{2}",
				Environment.Version.Major,
				Environment.Version.Minor,
				Environment.Version.Build);

			string s = Arguments;

			if (s.Length > 0)
			{
				Utility.PushColor(ConsoleColor.Yellow);
				Console.WriteLine("Core: Running with arguments: {0}", s);
				Utility.PopColor();
			}

			m_ProcessorCount = Environment.ProcessorCount;

			if (m_ProcessorCount > 1)
			{
				m_MultiProcessor = true;
			}

			if (m_MultiProcessor || Is64Bit)
			{
				Utility.PushColor(ConsoleColor.Green);
				Console.WriteLine(
					"Core: Optimizing for {0} {2}processor{1}",
					m_ProcessorCount,
					m_ProcessorCount == 1 ? "" : "s",
					Is64Bit ? "64-bit " : "");
				Utility.PopColor();
			}

			var platform = (int)Environment.OSVersion.Platform;

			if (platform == 4 || platform == 128)
			{
				// MS 4, MONO 128
				m_Unix = true;
				Utility.PushColor(ConsoleColor.Yellow);
				Console.WriteLine("Core: Unix environment detected");
				Utility.PopColor();
			}
			else
			{
				m_ConsoleEventHandler = OnConsoleEvent;
				UnsafeNativeMethods.SetConsoleCtrlHandler(m_ConsoleEventHandler, true);
			}

			if (GCSettings.IsServerGC)
			{
				Utility.PushColor(ConsoleColor.DarkYellow);
				Console.WriteLine("Core: Server garbage collection mode enabled");
				Utility.PopColor();
			}

			if (m_UseHRT)
			{
				Console.WriteLine(
					"Core: Requested high resolution timing ({0})", UsingHighResolutionTiming ? "Supported" : "Unsupported");
			}

			Console.WriteLine("RandomImpl: {0} ({1})", RandomImpl.Type.Name, RandomImpl.IsHardwareRNG ? "Hardware" : "Software");

			while (!ScriptCompiler.Compile(m_Debug, m_Cache))
			{
				Utility.PushColor(ConsoleColor.Red);
				Console.WriteLine("Scripts: One or more scripts failed to compile or no script files were found.");
				Utility.PopColor();

				if (m_Service)
				{
					return;
				}

				Console.WriteLine(" - Press return to exit, or R to try again.");

				if (Console.ReadKey(true).Key != ConsoleKey.R)
				{
					return;
				}
			}

			ScriptCompiler.Invoke("Configure");

			Region.Load();
			World.Load();

			ScriptCompiler.Invoke("Initialize");

			MessagePump messagePump = m_MessagePump = new MessagePump();

			timerThread.Start();

			foreach (Map m in Map.AllMaps)
			{
				m.Tiles.Force();
			}

			NetState.Initialize();

			EventSink.InvokeServerStarted();

			try
			{
				long now, last = TickCount;

				const int sampleInterval = 100;
				const float ticksPerSecond = (float)(1000 * sampleInterval);

				long sample = 0;

				while (!m_Closing)
				{
					m_Signal.WaitOne();

					Mobile.ProcessDeltaQueue();
					Item.ProcessDeltaQueue();

					Timer.Slice();
					messagePump.Slice();

					NetState.FlushAll();
					NetState.ProcessDisposedQueue();

					if (Slice != null)
					{
						Slice();
					}

					if ((++sample % sampleInterval) == 0)
					{
						now = TickCount;
						m_CyclesPerSecond[m_CycleIndex++ % m_CyclesPerSecond.Length] = ticksPerSecond / (now - last);
						last = now;
					}
				}
			}
			catch (Exception e)
			{
				CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, true));
			}
		}
コード例 #41
0
        public static void Main(string[] args)
        {
#if !DEBUG
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
#endif
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);

            try {
                mThread   = Thread.CurrentThread;
                mProcess  = Process.GetCurrentProcess();
                mAssembly = Assembly.GetEntryAssembly();
                if (mThread != null)
                {
                    mThread.Name = "Core Thread";
                }

                Timer.TimerThread ttObj = new Timer.TimerThread();
                mTimerThread      = new Thread(new ThreadStart(ttObj.TimerMain));
                mTimerThread.Name = "Timer Thread";

                int width = Math.Min(100, Console.LargestWindowWidth - 2);
                Console.CursorVisible = false;
                Console.Clear();
                Console.WindowLeft = Console.WindowTop = 0;
                if (Console.WindowWidth < width)
                {
                    Console.WindowWidth = width;
                }

                LogoPrinter.PrefixColor = EConsoleColor.Blue;
                LogoPrinter.SufixColor  = EConsoleColor.Blue;
                LogoPrinter.TextColor   = EConsoleColor.Gray;
                LogoPrinter.PrintLogo();

                Version ver = mAssembly.GetName().Version;
                CConsole.StatusLine("Shaiya.Extended Server - Version {0}.{1}, Build {2}.{3}", ver.Major, ver.Minor, ver.Build, ver.Revision);

                mConsoleEventHandler = new ConsoleEventHandler(OnConsoleEvent);
                SetConsoleCtrlHandler(mConsoleEventHandler, true);

                mAppConf = new ApplicationSettings();
                mAppConf.ReadAll();

                Stopwatch watch = Stopwatch.StartNew();
                CConsole.Info("Connecting to SQL Server {0}...", mAppConf.Network["DB Server"]);
                mDatabase = new MySqlWrapper(mAppConf.Network["DB Server"], int.Parse(mAppConf.Network["DB Port"]), mAppConf.Network["DB User"], mAppConf.Network["DB Password"], mAppConf.Network["DB Database"]);
                MysqlError conRes = mDatabase.Prepare();
                if (conRes != MysqlError.None)
                {
                    CConsole.WriteLine(EConsoleColor.Error, " failed!");
                    throw new Exception("Failed to open Database Connection! Type: " + conRes.ToString());
                }
                watch.Stop();
                CConsole.WriteLine(EConsoleColor.Status, " done! Needed {0:F2} sec", watch.Elapsed.TotalSeconds);
                watch = null;

                ScriptDatabase.Initialize(@"Scripts\ScriptList.xml");
                ScriptCompiler.Compile(AppDomain.CurrentDomain.BaseDirectory + Path.Combine(Settings.Default.MainConfDir, Settings.Default.ScriptAssemblies), true, true);

                World.Load();

                // testing CallMethod
                ScriptCompiler.CallMethod("Initialize");

                SocketPool.Create();
                mSocketConnector = new SocketConnector(mAppConf.Network["Server IP"], mAppConf.Network.GetInt("Server Port"));
                PacketHandlers.Initialize();

                // start Timer Thread
                mTimerThread.Start();

                NetState.Initialize();

                // finished Loading
                Events.InvokeServerStarted();


                DateTime    now, last = DateTime.Now;
                const int   sampleInterval = 100;
                const float ticksPerSecond = (float)(TimeSpan.TicksPerSecond * sampleInterval);
                int         sample         = 0;

                while (mSignal.WaitOne())
                {
                    Timer.Slice();
                    mSocketConnector.Slice();

                    NetState.FlushAll();
                    NetState.ProcessDisposedQueue();

                    if (Slice != null)
                    {
                        Slice();
                    }

                    // just for Diagnostics
                    if ((++sample % sampleInterval) == 0)
                    {
                        now = DateTime.Now;
                        mCyclesPerSecond[mCycleIndex++ % mCyclesPerSecond.Length] = ticksPerSecond / (now.Ticks - last.Ticks);
                        last = now;
                    }
                }
            } catch (Exception e) {
                CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, true));
            }
        }