Ejemplo n.º 1
0
        private static void HandleClosed()
        {
            if (m_Closing)
            {
                return;
            }

            m_Closing = true;

            Console.Write("Exiting...");

            if (!m_Crashed)
            {
                EventSink.InvokeShutdown(new ShutdownEventArgs());
            }

            if (SocketPool.Created)
            {
                SocketPool.Destroy();
            }

            Timer.TimerThread.Set();

            Console.WriteLine("done");
        }
Ejemplo n.º 2
0
		internal FileNodeSocketProxy(URL url)
		{
			container = new ServiceContainer();
			IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(url.Host), url.Port);
			pool = new SocketPool(container, endPoint);
			chunkCache = new Cache<string, byte[]>(60000); //one minute
		}
Ejemplo n.º 3
0
        public void SendAsync(byte[] bytes)
        {
            if (IsClient)
            {
                var block     = BufferPool.Pop();
                var writeArgs = SocketPool.Pop();

                // TODO: loop in case byte[] is greater than block capacity!!!
                var writeSize = (bytes.Length < block.Capacity) ? bytes.Length : block.Capacity;
                System.Buffer.BlockCopy(bytes, 0, block.Bytes, block.Offset, writeSize);
                ((MiniNet.Buffers.Buffer)block).Size = writeSize;

                writeArgs.UserToken    = block;
                writeArgs.AcceptSocket = BaseSocket;
                writeArgs.SetBuffer(block.Bytes, block.Offset, block.Size);
                writeArgs.Completed += OnSocketCompleted;

                var willRaiseEvent = BaseSocket.SendAsync(writeArgs);
                if (!willRaiseEvent)
                {
                    SendHandle(writeArgs);
                }
            }
            else
            {
                RaiseFault("Only accepted client sockets may read and write.");
            }
        }
Ejemplo n.º 4
0
 public CSocket(IPEndPoint _endPoint, SocketPool _pool, SocketPoolProfile config)
 {
     socketConfig = config;
     endpoint = _endPoint;
     pool = _pool;
     System.Net.Sockets.Socket _socket = new System.Net.Sockets.Socket(_endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
     _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, (int)config.SendTimeout.TotalMilliseconds);
     _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 24 * 3600 * 1000/*one day*/);//(int)config.ReceiveTimeout.TotalMilliseconds);
     _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, !config.Nagle);
     _socket.Connect(_endPoint);
     socket = _socket;
     this.inputStream = new BufferedStream(new NetworkStream(this.socket), config.BufferSize);
     Thread th = new Thread(delegate() {
         while (true)
         {
             try
             {
                 Receive();
             }
             catch (Exception ex)
             {
                 logger.Notice(ex.Message);
             }
         }
     });
     th.Start();
 }
Ejemplo n.º 5
0
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = e.ExceptionObject as Exception;

            CConsole.Write(EConsoleColor.Error, e.IsTerminating ? "Error: " : "Warning: ");
            CConsole.WriteLine(EConsoleColor.Error, ex.Message);
            if (ex.StackTrace != string.Empty)
            {
                CConsole.WriteLine(ex.StackTrace);
            }

            if (e.IsTerminating)
            {
                mCrashed = true;
                bool close = false;
                try {
                    CrashedEventArgs args = new CrashedEventArgs(e.ExceptionObject as Exception);
                    Events.InvokeCrashed(args);
                    close = args.Close;
                } catch {
                }

                if (!close)
                {
                    SocketPool.Destroy();

                    CConsole.ErrorLine("This exception is fatal, press return to exit");
                    CConsole.Read();
                }

                mClosing = true;
            }
        }
Ejemplo n.º 6
0
        internal FileNodeSocketProxy(URL url)
        {
            container = new ServiceContainer();
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(url.Host), url.Port);

            pool       = new SocketPool(container, endPoint);
            chunkCache = new Cache <string, byte[]>(60000);            //one minute
        }
Ejemplo n.º 7
0
        public void Pool_object_should_stock_when_dispose()
        {
            var sockets = new SocketPool(new Uri("http://www.baidu.com"));
            var socket  = sockets.AcquireItem();

            socket.Dispose();
            Assert.True(socket.Connected);
        }
Ejemplo n.º 8
0
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Console.WriteLine(e.IsTerminating ? "Error:" : "Warning:");
            Console.WriteLine(e.ExceptionObject);

            if (e.IsTerminating)
            {
                m_Crashed = true;

                bool close = false;

                try
                {
                    CrashedEventArgs args = new CrashedEventArgs(e.ExceptionObject as Exception);

                    EventSink.InvokeCrashed(args);

                    close = args.Close;
                }
                catch
                {
                }

                if (!close && !m_Service)
                {
                    try
                    {
                        for (int i = 0; i < m_MessagePump.Listeners.Length; i++)
                        {
                            m_MessagePump.Listeners[i].Dispose();
                        }
                    }
                    catch
                    {
                    }

                    if (SocketPool.Created)
                    {
                        SocketPool.Destroy();
                    }

                    if (m_Service)
                    {
                        Console.WriteLine("This exception is fatal.");
                    }
                    else
                    {
                        Console.WriteLine("This exception is fatal, press return to exit");
                        Console.ReadLine();
                    }
                }

                m_Closing = true;
            }
        }
Ejemplo n.º 9
0
        private void StartReceive()
        {
            SocketAsyncEventArgs args = SocketPool.Get();

            args.Completed += OperationCompleted;

            if (!Connection.ReceiveAsync(args))
            {
                OperationCompleted(this, args);
            }
        }
Ejemplo n.º 10
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="maxConn"></param>
 /// <param name="receiveBufferSize"></param>
 /// <param name="getIp"></param>
 public void setListener(int maxConn, int receiveBufferSize, ClientConnectedHandler getIp)
 {
     ServerState = WorkStatus.ServerInitialing;
     connCount   = 0;
     MaxClient   = maxConn;
     Clients     = new SocketPool();
     SemaphoreAcceptedClients = new Semaphore(ConnectionCount, MaxClient);
     SocketBuffer             = new BufferManager(receiveBufferSize * maxConn, receiveBufferSize);
     CommProtocol             = new CommunicationProtocol();
     ClientConnected          = getIp;
 }
Ejemplo n.º 11
0
        public void Pool_object_should_dispose_when_pool_release()
        {
            var sockets = new SocketPool(new Uri("http://www.baidu.com"));
            var socket  = sockets.AcquireItem();

            sockets.ReleaseAll();
            Assert.True(sockets.IsDisposed);

            socket.Dispose();
            Assert.False(socket.Connected);
        }
Ejemplo n.º 12
0
		private PooledSocket(Socket socket, SocketPool pool, BinaryFormatter formatter)
		{
			this.formatter = formatter;
			messageStream = new MemoryStream();
			this.socket = socket;
			writeLock = new object();
			this.pool = pool;
			socket.SendTimeout = 1000; //1 seconds :| is it okie?
			socket.NoDelay = true;
			socket.DontFragment = true;
			socket.LingerState.Enabled = false;
			ReadBuffer(4, HEADER);
		}
Ejemplo n.º 13
0
        private void ReleaseSocketArgs(SocketAsyncEventArgs args)
        {
            if (args != null)
            {
                args.Completed -= OnSocketCompleted; // clear previously attached event.

                // On Microsoft's AcceptSocket page, it says,
                // "If not supplied (set to null) before calling the Socket.AcceptAsync method, a new socket will be created automatically."
                // The "new socket is constructed with the same AddressFamily, SocketType, and ProtocolType as the current socket",
                // which is the listening socket.
                args.AcceptSocket = null;
                args.UserToken    = null;

                SocketPool.Push(args);
            }
        }
Ejemplo n.º 14
0
 public Connection Connect(Uri uri)
 {
     if (uri == null)
     {
         throw new ArgumentNullException("uri");
     }
     lock (_sync) {
         SocketPool pool;
         if (!_sockets.TryGetValue(uri.AbsoluteUri, out pool))
         {
             pool = new SocketPool(uri);
             _sockets.Add(uri.AbsoluteUri, pool);
         }
         var socket = pool.AcquireItem();
         return(new Connection(socket));
     }
 }
Ejemplo n.º 15
0
 public void AcceptAsync()
 {
     if (!IsClient)
     {
         var acceptArgs = SocketPool.Pop();
         acceptArgs.Completed += OnSocketCompleted;
         var willRaiseEvent = BaseSocket.AcceptAsync(acceptArgs);
         if (!willRaiseEvent)
         {
             AcceptHandle(acceptArgs);
         }
     }
     else
     {
         RaiseFault("Unable to create connections on a client socket.");
     }
 }
Ejemplo n.º 16
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="config">Configuration.Configuration object</param>
 public Dispatcher(Configuration.ServiceConfig config)
 {
     logger.Info("starting init servers");
     foreach(var server in config.Servers)
     {
         if (server.WeithtRate > 0)
         {
             var s = new Server(server);
             if (s.State != ServerState.Disable)
             {
                 SocketPool sp = new SocketPool(s, config.SocketPool);
                 s.ScoketPool = sp;
                 ServerPool.Add(s);
             }
         }
     }
     logger.Info("init servers end");
 }
Ejemplo n.º 17
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="config">Configuration.Configuration object</param>
 public Dispatcher(Configuration.ServiceConfig config)
 {
     logger.Info("starting init servers");
     foreach (var server in config.Servers)
     {
         if (server.WeithtRate > 0)
         {
             var s = new Server(server);
             if (s.State != ServerState.Disable)
             {
                 SocketPool sp = new SocketPool(s, config.SocketPool);
                 s.ScoketPool = sp;
                 ServerPool.Add(s);
             }
         }
     }
     logger.Info("init servers end");
 }
Ejemplo n.º 18
0
        /// <summary>
        /// This method corresponds to the "stats" command in the memcached protocol.
        /// It will send the stats command to the server that corresponds to the given key, hash or host,
        /// and return a Dictionary containing the results of the command.
        /// </summary>

        protected override Dictionary <string, string> stats(SocketPool pool)
        {
            if (pool == null)
            {
                return(null);
            }
            Dictionary <string, string> result = new Dictionary <string, string>();

            serverPool.Execute(pool, delegate(PooledSocket socket) {
                socket.Write("stats\r\n");
                string line;
                while (!(line = socket.ReadResponse().TrimEnd('\0', '\r', '\n')).StartsWith("END"))
                {
                    string[] s = line.Split(' ');
                    result.Add(s[1], s[2]);
                }
            });
            return(result);
        }
Ejemplo n.º 19
0
        public static void Main(string[] args)
        {
            int 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 " : "");
            }

            SocketPool.Create();
            PacketskHandler packetsHandler = new PacketskHandler();

            while (m_Signal.WaitOne())
            {
            }
        }
Ejemplo n.º 20
0
        private static void HandleClosed()
        {
            if (mClosing)
            {
                return;
            }

            if (!mCrashed)
            {
                Events.InvokeShutdown(new ShutdownEventArgs());
            }

            mClosing = true;
            CConsole.StatusLine("Exiting...");

            // do some kills
            SocketPool.Destroy();

            CConsole.StatusLine("Exiting finished! Press any Key to close.");
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GAF.Net.EvaluationClient"/> class.
        /// </summary>
        /// <param name="endPoints">End points.</param>
        public EvaluationClient(List <IPEndPoint> endPoints, string fitnessAssemblyName)
        {
            if (endPoints == null)
            {
                throw new ArgumentNullException(nameof(endPoints), "The parameter is null.");
            }

            if (string.IsNullOrWhiteSpace(fitnessAssemblyName))
            {
                throw new ArgumentException("The specified fitness assembly name is null or empty.", nameof(fitnessAssemblyName));
            }

            _socketPool = new SocketPool(endPoints);
            _pcQueue    = new GAF.Network.Threading.ProducerConsumerQueue(endPoints.Count);

            _fitnessAssemblyName = fitnessAssemblyName;
            _fitnessAssembly     = new FitnessAssembly(fitnessAssemblyName);

            InitialiseServers(true);
        }
Ejemplo n.º 22
0
        public PooledSocket(SocketPool socketPool, IPEndPoint endPoint, int sendReceiveTimeout)
        {
            this.socketPool = socketPool;
            Created = DateTime.Now;

            //Set up the socket.
            socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, sendReceiveTimeout);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, sendReceiveTimeout);
            socket.ReceiveTimeout = sendReceiveTimeout;
            socket.SendTimeout = sendReceiveTimeout;

            //Do not use Nagle's Algorithm
            socket.NoDelay = true;

            //Establish connection
            socket.Connect(endPoint);

            //Wraps two layers of streams around the socket for communication.
            stream = new BufferedStream(new NetworkStream(socket, false));
        }
Ejemplo n.º 23
0
		private void OnServiceRequest(IAsyncResult ar)
		{
			Socket client = null;
			try
			{
				client = serviceSocket.EndAccept(ar);
			}
			catch (Exception e)
			{
				Log.WriteLog("WCF: Error while accept connection: " + e);
				
			}
			try
			{
				if (serviceSocket != null)
				{
					serviceSocket.BeginAccept(new AsyncCallback(OnServiceRequest), null);
				}
			}
			catch (Exception e)
			{
				Log.WriteLog("WCF: Error while listen more connections: " + e);
				
			}
			if (client != null)
			{
				var pool = new SocketPool(container, client); ; 
				poolsLock.EnterWriteLock();
				try
				{
					pools.Add(pool);
				}
				finally 
				{
					poolsLock.ExitWriteLock();
				}
			}
		}
Ejemplo n.º 24
0
        public void ReceiveAsync()
        {
            if (IsClient)
            {
                var block    = BufferPool.Pop();
                var readArgs = SocketPool.Pop();

                readArgs.UserToken    = block;
                readArgs.AcceptSocket = BaseSocket;
                readArgs.SetBuffer(block.Bytes, block.Offset, block.Capacity);
                readArgs.Completed += OnSocketCompleted;

                var willRaiseEvent = BaseSocket.ReceiveAsync(readArgs);
                if (!willRaiseEvent)
                {
                    ReceiveHandle(readArgs);
                }
            }
            else
            {
                RaiseFault("Only accepted client sockets may read and write.");
            }
        }
Ejemplo n.º 25
0
        private void OperationCompleted(object sender, SocketAsyncEventArgs e)
        {
            e.Completed -= OperationCompleted;

            switch (e.LastOperation)
            {
            case SocketAsyncOperation.Receive:
                ProcessNetwork(e);

                SocketPool.Add(e);
                break;

            case SocketAsyncOperation.Send:
                IPacket packet = e.UserToken as IPacket;

                if (packet is DisconnectPacket)
                {
                    Server.DisconnectClient(this);
                }

                e.SetBuffer(null, 0, 0);
                break;

            case SocketAsyncOperation.Disconnect:
                Connection.Close();

                break;
            }

            if (Connection != null)
            {
                if (!Connection.Connected && !Disconnected)
                {
                    Server.DisconnectClient(this);
                }
            }
        }
Ejemplo n.º 26
0
        private void OnServiceRequest(IAsyncResult ar)
        {
            Socket client = null;

            try
            {
                client = serviceSocket.EndAccept(ar);
            }
            catch (Exception e)
            {
                Log.WriteLog("WCF: Error while accept connection: " + e);
            }
            try
            {
                if (serviceSocket != null)
                {
                    serviceSocket.BeginAccept(new AsyncCallback(OnServiceRequest), null);
                }
            }
            catch (Exception e)
            {
                Log.WriteLog("WCF: Error while listen more connections: " + e);
            }
            if (client != null)
            {
                var pool = new SocketPool(container, client);;
                poolsLock.EnterWriteLock();
                try
                {
                    pools.Add(pool);
                }
                finally
                {
                    poolsLock.ExitWriteLock();
                }
            }
        }
Ejemplo n.º 27
0
		public static PooledSocket CreateNewSocket(EndPoint endpoint, SocketPool pool, TotalFormatter formatter)
		{
			try
			{
				var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
				socket.Connect(endpoint);
				return new PooledSocket(socket, pool, formatter);
			}
			catch
			{
				return null;
			}
		}
Ejemplo n.º 28
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(Console.Out, 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);
            }

            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_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));
            }
        }
Ejemplo n.º 29
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
        }
 public RedisPooledSocket(SocketPool pool)
 {
     _pool = pool;
 }
Ejemplo n.º 31
0
		public static PooledSocket CreateNewSocket(string host, int port, SocketPool pool, BinaryFormatter formatter)
		{
			try
			{
				var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
				socket.Connect(host, port);
				return new PooledSocket(socket, pool, formatter);
			}
			catch
			{
				return null;
			}
		}
Ejemplo n.º 32
0
		public static PooledSocket CreateNewSocket(Socket socket, SocketPool pool, BinaryFormatter formatter)
		{
			return new PooledSocket(socket, pool, formatter);
		}
Ejemplo n.º 33
0
        private BinaryResponse[] executeBulk(BinaryRequest quietTemplate, BinaryRequest finalRequestTemplate,
                                             string[] keys, uint[] hashes)
        {
            EnsureAlignment(keys, hashes);

            //Group the keys/hashes by server(pool)
            Dictionary <SocketPool, Dictionary <string, List <int> > > dict =
                new Dictionary <SocketPool, Dictionary <string, List <int> > >();

            for (int i = 0; i < keys.Length; i++)
            {
                Dictionary <string, List <int> > getsForServer;
                SocketPool pool = serverPool.GetSocketPool(hashes[i]);
                if (!dict.TryGetValue(pool, out getsForServer))
                {
                    dict[pool] = getsForServer = new Dictionary <string, List <int> >();
                }

                List <int> positions;
                if (!getsForServer.TryGetValue(keys[i], out positions))
                {
                    getsForServer[keyPrefix + keys[i]] = positions = new List <int>();
                }
                positions.Add(i);
            }

            //Get the values
            BinaryResponse[] returnValues = new BinaryResponse[keys.Length];
            foreach (KeyValuePair <SocketPool, Dictionary <string, List <int> > > kv in dict)
            {
                Dictionary <UInt32, string> opaqueToKey = new Dictionary <UInt32, string>();
                serverPool.Execute(kv.Key, delegate(PooledSocket socket) {
                    int i     = 0;
                    int total = kv.Value.Count;
                    socket.ResetSequence();
                    UInt32 sequence    = socket.NextSequence;
                    UInt32 minSequence = sequence;
                    foreach (var value in kv.Value)
                    {
                        BinaryRequest req;
                        req                   = i++ + 1 < total ? quietTemplate.Clone() : finalRequestTemplate;
                        req.KeyAsString       = value.Key;
                        req.Opaque            = sequence;
                        opaqueToKey[sequence] = value.Key;
                        sequence              = socket.NextSequence;
                        socket.Write(req);
                    }
                    var responses = socket.ReadBinaryResponseBetween(minSequence, sequence - 1);

                    //Read values, one by one
                    foreach (var response in responses)
                    {
                        var gottenKey = opaqueToKey[response.Opaque];
                        foreach (int position in kv.Value[gottenKey])
                        {
                            returnValues[position] = response;
                        }
                    }
                });
            }
            return(returnValues);
        }
Ejemplo n.º 34
0
 public MyProxy(SocketPool pool)
 {
     this.pool = pool;
 }
Ejemplo n.º 35
0
 protected override Dictionary <string, string> stats(SocketPool pool)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 36
0
        private void ProcessNetwork(SocketAsyncEventArgs e)
        {
            if (Connection == null || !Connection.Connected)
            {
                return;
            }

            if (e.SocketError == SocketError.Success && e.BytesTransferred > 0)
            {
                SocketAsyncEventArgs newArgs = SocketPool.Get();
                newArgs.Completed += OperationCompleted;

                if (!Connection.ReceiveAsync(newArgs))
                {
                    OperationCompleted(this, newArgs);
                }

                try
                {
                    sem.Wait(500, cancel.Token);
                }
                catch (OperationCanceledException)
                {
                }
                catch (NullReferenceException)
                {
                }
                catch (TimeoutException)
                {
                    Server.DisconnectClient(this);
                    return;
                }

                var packets = PacketReader.ReadPackets(this, e.Buffer, e.Offset, e.BytesTransferred);
                try
                {
                    foreach (IPacket packet in packets)
                    {
                        if (PacketHandlers[packet.ID] != null)
                        {
                            try
                            {
                                PacketHandlers[packet.ID](packet, this, Server);
                            }
                            catch (PlayerDisconnectException)
                            {
                                Server.DisconnectClient(this);
                            }
                            catch (Exception ex)
                            {
                                Server.Log(LogCategory.Debug, "Disconnecting client due to exception in network worker");
                                Server.Log(LogCategory.Debug, ex.ToString());

                                Server.DisconnectClient(this);
                            }
                        }
                        else
                        {
                            Log("Unhandled packet {0}", packet.GetType().Name);
                        }
                    }
                }
                catch (NotSupportedException)
                {
                    Server.Log(LogCategory.Debug, "Disconnecting client due to unsupported packet received.");
                    return;
                }

                if (sem != null)
                {
                    sem.Release();
                }
            }
            else
            {
                Server.DisconnectClient(this);
            }
        }
Ejemplo n.º 37
0
 public MyProxy(SocketPool pool)
 {
     this.pool = pool;
 }
Ejemplo n.º 38
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
        }
        /// <summary>
        /// Create a new connection pool
        /// </summary>
        /// <param name="endPoint">Redis server</param>
        /// <param name="max">Maximum simultaneous connections</param>

        public RedisConnectionPool(EndPoint endPoint, int max)
        {
            _pool     = new SocketPool(endPoint, max);
            _endPoint = endPoint;
        }
Ejemplo n.º 40
0
        /// <summary>
        /// This method executes a multi-get. It will group the keys by server and execute a single get
        /// for each server, and combine the results. The returned object[] will have the same size as
        /// the given key array, and contain either null or a value at each position according to
        /// the key on that position.
        /// </summary>
        protected override object[] get(string command, string[] keys, bool keysAreChecked, uint[] hashes, out ulong[] uniques)
        {
            EnsureAlignment(keys, hashes);
            uniques = new ulong[keys.Length];

            //Avoid going through the server grouping if there's only one key.
            if (keys.Length == 1)
            {
                return(new object[] { get(command, keys[0], keysAreChecked, hashes[0], out uniques[0]) });
            }

            //Check keys.
            if (!keysAreChecked)
            {
                for (int i = 0; i < keys.Length; i++)
                {
                    checkKey(keys[i]);
                }
            }

            //Group the keys/hashes by server(pool)
            Dictionary <SocketPool, Dictionary <string, List <int> > > dict =
                new Dictionary <SocketPool, Dictionary <string, List <int> > >();

            for (int i = 0; i < keys.Length; i++)
            {
                Dictionary <string, List <int> > getsForServer;
                SocketPool pool = serverPool.GetSocketPool(hashes[i]);
                if (!dict.TryGetValue(pool, out getsForServer))
                {
                    dict[pool] = getsForServer = new Dictionary <string, List <int> >();
                }

                List <int> positions;
                if (!getsForServer.TryGetValue(keys[i], out positions))
                {
                    getsForServer[keyPrefix + keys[i]] = positions = new List <int>();
                }
                positions.Add(i);
            }

            //Get the values
            object[] returnValues = new object[keys.Length];
            ulong[]  _uniques     = new ulong[keys.Length];
            foreach (KeyValuePair <SocketPool, Dictionary <string, List <int> > > kv in dict)
            {
                serverPool.Execute(kv.Key, delegate(PooledSocket socket) {
                    //Build the get request
                    StringBuilder getRequest = new StringBuilder(command);
                    foreach (KeyValuePair <string, List <int> > key in kv.Value)
                    {
                        getRequest.Append(" ");
                        getRequest.Append(key.Key);
                    }
                    getRequest.Append("\r\n");

                    //Send get request
                    socket.Write(getRequest.ToString());

                    //Read values, one by one
                    object gottenObject;
                    string gottenKey;
                    ulong unique;
                    while (readValue(socket, out gottenObject, out gottenKey, out unique))
                    {
                        foreach (int position in kv.Value[gottenKey])
                        {
                            returnValues[position] = gottenObject;
                            _uniques[position]     = unique;
                        }
                    }
                });
            }
            uniques = _uniques;
            return(returnValues);
        }