Ejemplo n.º 1
0
        /// <summary>
        /// 初始化管理
        /// </summary>
        /// <param name="maxConnectionCount">允许的最大连接数</param>
        /// <param name="initConnectionResourceCount">启动时初始化多少个连接的资源</param>
        /// <param name="socketProtocol">socket应用层协议</param>
        /// <param name="singleBufferMaxSize">每个 socket 读写缓存最大字节数, 默认为8k</param>
        /// <param name="sendTimeOut">socket 发送超时时长, 以毫秒为单位</param>
        /// <param name="receiveTimeOut">socket 接收超时时长, 以毫秒为单位</param>
        /// <returns></returns>
        public virtual async Task InitAsync(int maxConnectionCount, int initConnectionResourceCount
                                            , ISocketProtocol socketProtocol, int singleBufferMaxSize = 8 * 1024
                                            , int sendTimeOut = 10000, int receiveTimeOut = 10000)
        {
            maxConnCount = maxConnectionCount;
            this.initConnectionResourceCount = initConnectionResourceCount;
            this.singleBufferMaxSize         = singleBufferMaxSize;
            this.sendTimeOut    = sendTimeOut;
            this.receiveTimeOut = receiveTimeOut;

            await Task.Run(() =>
            {
                semaphore = new Semaphore(maxConnCount, maxConnCount);
                //设置初始线程数为cpu核数*2
                connectedClients = new ConcurrentDictionary <Guid, IOCPClient>(Environment.ProcessorCount * 2, maxConnCount);
                //读写分离, 每个socket连接需要2个SocketAsyncEventArgs.
                var saePool    = new SocketAsyncEventArgsPool(initConnectionResourceCount * 2, SendReceiveArgsCompleted, singleBufferMaxSize);
                iocpClientPool = new IOCPClientPool(initConnectionResourceCount, saePool);
            });
        }