Exemple #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();

            InstanceID = mInstanceID++;
            Instances.Add(InstanceID, this);

            try {
                mAddress = ((IPEndPoint)mSocket.RemoteEndPoint).Address;
            } catch (Exception ex) {
                ExceptionHandler.Trace(ex);
                mAddress = IPAddress.None;
            }

            mConnectedOn = DateTime.Now;

            if (mCreatedCallback != null)
            {
                mCreatedCallback(this);
            }
        }
Exemple #2
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 {
						ServerConsole.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) {
							ServerConsole.StatusLine(String.Format("# {0}:{1}", ip[i], ipep.Port));
							IPs.Add(ip[i]);
							Ports.Add(ipep.Port);
						}
					} catch {
					}
				} else {
					IPs.Add(ipep.Address);
					Ports.Add(ipep.Port);
					if (ipep.Address.ToString() != Connector.IP) {
						ServerConsole.StatusLine(String.Format("start listen on {0} -> {1}:{2}", Connector.IP, ipep.Address, ipep.Port));
					} else {
						ServerConsole.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
						ServerConsole.ErrorLine(String.Format("Listener Failed: {0} -> {1}:{2} (In Use)", Connector.IP, ipep.Address, ipep.Port));
					} else if (se.ErrorCode == 10049) { // WSAEADDRNOTAVAIL
						ServerConsole.ErrorLine(String.Format("Listener Failed: {0} -> {1}:{2} (Unavailable)", Connector.IP, ipep.Address, ipep.Port));
					} else {
						ServerConsole.ErrorLine("Listener Exception:");
						ServerConsole.WriteLine(e);
					}
				}

				return null;
			}
		}
Exemple #3
0
		public SocketListener(IPEndPoint ipep, SocketConnector Connector) {
			IPs = new List<IPAddress>();
			Ports = new List<int>();

			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!");
		}
        public SocketListener(IPEndPoint ipep, SocketConnector Connector)
        {
            IPs   = new List <IPAddress>();
            Ports = new List <int>();

            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!");
            }
        }
        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 {
                        ServerConsole.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)
                        {
                            ServerConsole.StatusLine(String.Format("# {0}:{1}", ip[i], ipep.Port));
                            IPs.Add(ip[i]);
                            Ports.Add(ipep.Port);
                        }
                    } catch {
                    }
                }
                else
                {
                    IPs.Add(ipep.Address);
                    Ports.Add(ipep.Port);
                    if (ipep.Address.ToString() != Connector.IP)
                    {
                        ServerConsole.StatusLine(String.Format("start listen on {0} -> {1}:{2}", Connector.IP, ipep.Address, ipep.Port));
                    }
                    else
                    {
                        ServerConsole.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
                    {
                        ServerConsole.ErrorLine(String.Format("Listener Failed: {0} -> {1}:{2} (In Use)", Connector.IP, ipep.Address, ipep.Port));
                    }
                    else if (se.ErrorCode == 10049)                         // WSAEADDRNOTAVAIL
                    {
                        ServerConsole.ErrorLine(String.Format("Listener Failed: {0} -> {1}:{2} (Unavailable)", Connector.IP, ipep.Address, ipep.Port));
                    }
                    else
                    {
                        ServerConsole.ErrorLine("Listener Exception:");
                        ServerConsole.WriteLine(e);
                    }
                }

                return(null);
            }
        }
Exemple #6
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
		}
Exemple #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();

			InstanceID = mInstanceID++;
			Instances.Add(InstanceID, this);

			try {
				mAddress = ((IPEndPoint)mSocket.RemoteEndPoint).Address;
			} catch (Exception ex) {
				ExceptionHandler.Trace(ex);
				mAddress = IPAddress.None;
			}

			mConnectedOn = DateTime.Now;

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