public void PooledBufferManagerThrowsWhenParamsAreInvalid(int maxLength, int maxArraysPerBucket)
 {
     Assert.Throws <ArgumentOutOfRangeException>(() =>
     {
         var m = new PooledBufferManager(maxLength, maxArraysPerBucket);
     });
 }
예제 #2
0
 protected Server()
 {
     _clients      = new List <Client>();
     BufferManager = new PooledBufferManager(BUFFER_SIZE, 1)
     {
         ClearOnReturn = false
     };
 }
예제 #3
0
파일: Server.cs 프로젝트: odasm/QuasarRAT
 /// <summary>
 /// Constructor of the server, initializes variables.
 /// </summary>
 protected Server()
 {
     _clients      = new List <Client>();
     BufferManager = new PooledBufferManager(BUFFER_SIZE, 1)
     {
         ClearOnReturn = false
     };
     AddTypesToSerializer(typeof(IMessage), PacketRegistry.GetPacketTypes(typeof(IMessage)).ToArray());
 }
        /// <inheritdoc />
        public void Dispose()
        {
            if (this.manager == null || this.Array == null)
            {
                return;
            }

            this.manager.Return(this.Array);
            this.manager = null;
            this.Array   = null;
        }
예제 #5
0
        /// <summary>
        /// config구조체로 초기화
        /// </summary>
        /// <param name="config"></param>
        private void Setup(TcpServiceConfig config)
        {
            // 콘솔 로거 생성
            if (config.Log != null)
            {
                if (config.Log.Equals("console", StringComparison.OrdinalIgnoreCase))
                {
                    this.Logger = new ConsoleLogger();
                }
                else if (config.Log.Equals("file", StringComparison.OrdinalIgnoreCase))
                {
                    this.Logger = new SimpleFileLogger(@"netservice.log");
                }
                else
                {
                    this.Logger = new NullLogger();
                }
            }
            else
            {
                this.Logger = new ConsoleLogger();
            }

            this.Logger.Level = LogLevel.Error;
            if (config.LogLevel != null)
            {
                this.Logger.Level = (LogLevel)Enum.Parse(typeof(LogLevel), config.LogLevel, true);
            }

            // 16, 128, 256, 1024, 4096 사이즈의 풀을 생성하는 설정
            int[] poolSizes = new int[] { 4096, 16, 128, 256, 1024 };
            this._pooledBufferManager = new PooledBufferManager(poolSizes);

            this.Config = config;
            if (Config.MessageFactoryTypeName != "")
            {
                try
                {
                    //TODO 테스트 필요
                    Type typeOfClass = Type.GetType("this.Config.MessageFactoryAssemblyName", true);
                    var  objHandle   = Activator.CreateInstance(typeOfClass);
                    _messageFactory = (laster40Net.Message.IMessageFactory)objHandle;//.Unwrap();
                }
                catch (Exception e)
                {
                    Logger.Log(LogLevel.Error, "메세지 팩토리 생성 실패", e);
                }
            }
        }
예제 #6
0
파일: Server.cs 프로젝트: CWIWC/xRAT
        /// <summary>
        /// Begins listening for clients.
        /// </summary>
        /// <param name="port">Port to listen for clients on.</param>
        public void Listen(ushort port)
        {
            this.Port = port;
            try
            {
                if (!Listening)
                {
                    lock (_clientsLock)
                    {
                        _clients = new List<Client>();
                    }

                    _item = new SocketAsyncEventArgs();
                    _item.Completed += AcceptClient;

                    if (_handle != null)
                    {
                        try
                        {
                            _handle.Close();
                        }
                        catch
                        {
                        }
                    }

                    if (BufferManager == null)
                        BufferManager = new PooledBufferManager(BUFFER_SIZE, 1) { ClearOnReturn = true };

                    _handle = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    _handle.Bind(new IPEndPoint(IPAddress.Any, port));
                    _handle.Listen(1000);

                    Processing = false;

                    Listening = true;
                    OnServerState(true);

                    if (!_handle.AcceptAsync(_item))
                        AcceptClient(null, _item);
                }
            }
            catch (Exception)
            {
                Disconnect();
            }
        }
예제 #7
0
 public ServerSession(Socket socket, SocketAsyncEventArgs recvSAEA, SocketAsyncEventArgs sendSAEA, PooledBufferManager pooledBufferManager)
     : base(socket, recvSAEA, sendSAEA, pooledBufferManager)
 {
 }
예제 #8
0
 /// <summary>
 /// Constructor of the server, initializes variables.
 /// </summary>
 protected Server()
 {
     _clients = new List<Client>();
     BufferManager = new PooledBufferManager(BUFFER_SIZE, 1) { ClearOnReturn = false };
 }
예제 #9
0
        /// <summary>
        /// Begins listening for clients.
        /// </summary>
        /// <param name="port">Port to listen for clients on.</param>
        public void Listen(ushort port)
        {
            if (PacketTypes.Count == 0) throw new Exception("No packet types added");

            this.Port = port;
            try
            {
                if (!Listening)
                {
                    lock (_clientsLock)
                    {
                        _clients = new List<Client>();
                    }

                    _item = new SocketAsyncEventArgs();
                    _item.Completed += AcceptClient;

                    if (_handle != null)
                    {
                        _handle.Close();
                    }

                    if (BufferManager == null)
                        BufferManager = new PooledBufferManager(BUFFER_SIZE, 1) { ClearOnReturn = true };

                    _handle = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    _handle.Bind(new IPEndPoint(IPAddress.Any, port));
                    _handle.Listen(1000);

                    _processing = false;

                    OnServerState(true);

                    if (!_handle.AcceptAsync(_item))
                        AcceptClient(null, _item);
                }
            }
            catch (SocketException ex)
            {
                if (ex.ErrorCode == 10048)
                {
                    MessageBox.Show("The port is already in use.", "Listen Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    MessageBox.Show(
                        string.Format(
                            "An unexpected socket error occurred: {0}\n\nError Code: {1}\n\nPlease report this as fast as possible here:\n{2}/issues",
                            ex.Message, ex.ErrorCode, Settings.RepositoryURL), "Unexpected Listen Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                Disconnect();
            }
            catch (Exception)
            {
                Disconnect();
            }
        }
예제 #10
0
        public virtual bool Init(ServerExecuteType executeType, string version, string name = null)
        {
            Running = new AtomicBool();
            Stopped = new AtomicBool();

            ExecuteType = executeType;
            Name        = string.IsNullOrEmpty(name) == true?Process.GetCurrentProcess().ProcessName : name;

            Version    = version;
            ModuleName = Name;

            CreateLogger();

            Logger.Info("Init");

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

            if (LoadServerConfig() == false)
            {
                if (ExecuteType == ServerExecuteType.Console)
                {
                    Console.ReadKey();
                }
                return(false);
            }

            TheadPoolEx.SetMinMaxThreads(
                m_ServerConfig.MinWorkerThreads == 0 ? Environment.ProcessorCount : m_ServerConfig.MinWorkerThreads,
                m_ServerConfig.MaxWorkerThreads == 0 ? Environment.ProcessorCount * 2: m_ServerConfig.MaxWorkerThreads,
                m_ServerConfig.MinCompletionPortThreads == 0 ? Environment.ProcessorCount : m_ServerConfig.MinCompletionPortThreads,
                m_ServerConfig.MaxCompletionPortThreads == 0 ? Environment.ProcessorCount * 2 : m_ServerConfig.MaxCompletionPortThreads);

            m_Sessions  = new ConcurrentDictionary <long, Session>();
            m_Listeners = new List <Listener>();

            try
            {
                int bufferSize = m_ServerConfig.ReceiveBufferSize;

                if (bufferSize <= 0)
                {
                    bufferSize = 1024 * 4;
                }

                // Send, Recv
                m_BufferManager = new BufferManager(bufferSize * m_ServerConfig.MaxConnectionNumber * 2, bufferSize);

                try
                {
                    m_BufferManager.InitBuffer();

                    int[] poolSizes = new int[] { 4096, 16, 128, 256, 1024 };
                    m_PooledBufferManager = new PooledBufferManager(poolSizes);

                    {
                        SocketAsyncEventArgs socketEventArg;
                        var socketArgsList = new List <SocketAsyncEventArgs>(m_ServerConfig.MaxConnectionNumber);

                        for (int i = 0; i < m_ServerConfig.MaxConnectionNumber; i++)
                        {
                            socketEventArg            = new SocketAsyncEventArgs();
                            socketEventArg.Completed += new EventHandler <SocketAsyncEventArgs>(CompletedReceive);
                            m_BufferManager.SetBuffer(socketEventArg);
                            socketArgsList.Add(socketEventArg);
                        }
                        m_RecvSAEAPool = new ConcurrentStack <SocketAsyncEventArgs>(socketArgsList);
                    }

                    {
                        SocketAsyncEventArgs socketEventArg;
                        var socketArgsList = new List <SocketAsyncEventArgs>(m_ServerConfig.MaxConnectionNumber);
                        for (int i = 0; i < m_ServerConfig.MaxConnectionNumber; i++)
                        {
                            socketEventArg            = new SocketAsyncEventArgs();
                            socketEventArg.Completed += new EventHandler <SocketAsyncEventArgs>(CompletedSend);
                            //m_BufferManager.SetBuffer(socketEventArg);
                            // Send할때 별도의 풀을 사용할거라서
                            socketEventArg.SetBuffer(null, 0, 0);
                            socketArgsList.Add(socketEventArg);
                        }
                        m_SendSAEAPool = new ConcurrentStack <SocketAsyncEventArgs>(socketArgsList);
                    }
                }
                catch (Exception e)
                {
                    Logger.Error("메모리 부족! 최대 접속 허용 인원 설정을 낮추세요", e);
                    if (ExecuteType == ServerExecuteType.Console)
                    {
                        Console.ReadKey();
                    }
                    return(false);
                }

                m_Updater = new TimerThread(Update, null, 1);

                return(true);
            }
            catch (Exception e)
            {
                Logger.Error("Server.Init", e);
                if (ExecuteType == ServerExecuteType.Console)
                {
                    Console.ReadKey();
                }
                return(false);
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="PooledByteBuffer"/> class.
 /// </summary>
 /// <param name="manager">The buffer manager</param>
 /// <param name="array">The byte array</param>
 /// <param name="length">The expected minimum length of the buffer</param>
 public PooledByteBuffer(PooledBufferManager manager, byte[] array, int length)
 {
     this.manager = manager;
     this.Array   = array;
     this.Length  = length;
 }