Example #1
0
        public NetState(Socket socket, SocketConnector messagePump)
        {
            mSocket      = socket;
            mBuffer      = new ByteQueue();
            mSeeded      = false;
            mRunning     = false;
            mRecvBuffer  = new byte[mBufferSize];
            mMessagePump = messagePump;

            mSendQueue = new SendQueue();
            UpdateAcitivty();

            mInstances.Add(this);

            try {
                mAddress  = IP.Intern(((IPEndPoint)mSocket.RemoteEndPoint).Address);
                mToString = mAddress.ToString();
            } catch (Exception ex) {
                ExceptionHandler.Trace(ex);
                mAddress  = IPAddress.None;
                mToString = "(error)";
            }

            mConnectedOn = DateTime.Now;

            if (mCreatedCallback != null)
            {
                mCreatedCallback(this);
            }
        }
Example #2
0
		public SocketListener( IPEndPoint ipep, SocketConnector Connector ) {
			mAccepted = new Queue<Socket>();
			mAcceptedSyncRoot = ( (ICollection)mAccepted ).SyncRoot;
			mOnAccept = new AsyncCallback( OnAccept );
			mListener = Bind( ipep, Connector );
			if( mListener == null ) 
				throw new Exception( "Could not bind IP to Socket! Please check your Network Configuration!" );
		}
Example #3
0
 public SocketListener(IPEndPoint ipep, SocketConnector Connector)
 {
     mAccepted         = new Queue <Socket>();
     mAcceptedSyncRoot = ((ICollection)mAccepted).SyncRoot;
     mOnAccept         = new AsyncCallback(OnAccept);
     mListener         = Bind(ipep, Connector);
     if (mListener == null)
     {
         throw new Exception("Could not bind IP to Socket! Please check your Network Configuration!");
     }
 }
Example #4
0
		private Socket Bind( IPEndPoint ipep, SocketConnector Connector ) {
			Socket s = SocketPool.AcquireSocket();

			try {
				s.LingerState.Enabled = false;
				s.ExclusiveAddressUse = false;

				s.Bind( ipep );
				s.Listen( 8 );

				if( ipep.Address.Equals( IPAddress.Any ) ) {
					try {
						CConsole.StatusLine( String.Format( "start listen on {0}:{1}", IPAddress.Loopback, ipep.Port ) );

						IPHostEntry iphe = Dns.GetHostEntry( Dns.GetHostName() );
						IPAddress[] ip = iphe.AddressList;
						for( int i = 0; i < ip.Length; ++i )
							CConsole.StatusLine( String.Format( "# {0}:{1}", ip[ i ], ipep.Port ) );
					} catch {
					}
				} else {
					if( ipep.Address.ToString() != Connector.IP )
						CConsole.StatusLine( String.Format( "start listen on {0} -> {1}:{2}", Connector.IP, ipep.Address, ipep.Port ) );
					else
						CConsole.StatusLine( String.Format( "start listen on {0}:{1}", ipep.Address, ipep.Port ) );
				}

				IAsyncResult res = s.BeginAccept( SocketPool.AcquireSocket(), 0, mOnAccept, s );
				return s;
			} catch( Exception e ) {
				/* TODO
				 * throws more Exceptions like this
				 */
				if( e is SocketException ) {
					SocketException se = (SocketException)e;

					if( se.ErrorCode == 10048 ) { // WSAEADDRINUSE
						CConsole.ErrorLine( String.Format( "Listener Failed: {0} -> {1}:{2} (In Use)", Connector.IP, ipep.Address, ipep.Port ) );
					} else if( se.ErrorCode == 10049 ) { // WSAEADDRNOTAVAIL
						CConsole.ErrorLine( String.Format( "Listener Failed: {0} -> {1}:{2} (Unavailable)", Connector.IP, ipep.Address, ipep.Port ) );
					} else {
						CConsole.ErrorLine( "Listener Exception:" );
						CConsole.WriteLine( e );
					}
				}

				return null;
			}
		}
Example #5
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 ) );
			}

		}
Example #6
0
        private Socket Bind(IPEndPoint ipep, SocketConnector Connector)
        {
            Socket s = SocketPool.AcquireSocket();

            try {
                s.LingerState.Enabled = false;
                s.ExclusiveAddressUse = false;

                s.Bind(ipep);
                s.Listen(8);

                if (ipep.Address.Equals(IPAddress.Any))
                {
                    try {
                        CConsole.StatusLine(String.Format("start listen on {0}:{1}", IPAddress.Loopback, ipep.Port));

                        IPHostEntry iphe = Dns.GetHostEntry(Dns.GetHostName());
                        IPAddress[] ip   = iphe.AddressList;
                        for (int i = 0; i < ip.Length; ++i)
                        {
                            CConsole.StatusLine(String.Format("# {0}:{1}", ip[i], ipep.Port));
                        }
                    } catch {
                    }
                }
                else
                {
                    if (ipep.Address.ToString() != Connector.IP)
                    {
                        CConsole.StatusLine(String.Format("start listen on {0} -> {1}:{2}", Connector.IP, ipep.Address, ipep.Port));
                    }
                    else
                    {
                        CConsole.StatusLine(String.Format("start listen on {0}:{1}", ipep.Address, ipep.Port));
                    }
                }

                IAsyncResult res = s.BeginAccept(SocketPool.AcquireSocket(), 0, mOnAccept, s);
                return(s);
            } catch (Exception e) {
                /* TODO
                 * throws more Exceptions like this
                 */
                if (e is SocketException)
                {
                    SocketException se = (SocketException)e;

                    if (se.ErrorCode == 10048)                        // WSAEADDRINUSE
                    {
                        CConsole.ErrorLine(String.Format("Listener Failed: {0} -> {1}:{2} (In Use)", Connector.IP, ipep.Address, ipep.Port));
                    }
                    else if (se.ErrorCode == 10049)                          // WSAEADDRNOTAVAIL
                    {
                        CConsole.ErrorLine(String.Format("Listener Failed: {0} -> {1}:{2} (Unavailable)", Connector.IP, ipep.Address, ipep.Port));
                    }
                    else
                    {
                        CConsole.ErrorLine("Listener Exception:");
                        CConsole.WriteLine(e);
                    }
                }

                return(null);
            }
        }
Example #7
0
		public NetState( Socket socket, SocketConnector messagePump ) {
			mSocket = socket;
			mBuffer = new ByteQueue();
			mSeeded = false;
			mRunning = false;
			mRecvBuffer = new byte[ mBufferSize ];
			mMessagePump = messagePump;

			mSendQueue = new SendQueue();
			UpdateAcitivty();

			mInstances.Add( this );

			try {
				mAddress = IP.Intern( ( (IPEndPoint)mSocket.RemoteEndPoint ).Address );
				mToString = mAddress.ToString();
			} catch( Exception ex ) {
				ExceptionHandler.Trace( ex );
				mAddress = IPAddress.None;
				mToString = "(error)";
			}

			mConnectedOn = DateTime.Now;

			if( mCreatedCallback != null )
				mCreatedCallback( this );
		}