/// <summary> /// 初始化管理 /// </summary> /// <param name="maxConnectionCount">允许的最大连接数</param> /// <param name="initConnectionResourceCount">启动时初始化多少个连接的资源</param> /// <param name="singleBufferMaxSize">每个 socket 读写缓存最大字节数, 默认为8k</param> /// <param name="sendTimeOut">socket 发送超时时长, 以毫秒为单位</param> /// <param name="receiveTimeOut">socket 接收超时时长, 以毫秒为单位</param> public virtual async Task InitAsync(int maxConnectionCount, int initConnectionResourceCount, ISocketBufferProcess bufferProcess, int singleBufferMaxSize = 8 * 1024 , int sendTimeOut = 10000, int receiveTimeOut = 10000) { this.maxConnCount = maxConnectionCount; this.initConnectionResourceCount = initConnectionResourceCount; this.singleBufferMaxSize = singleBufferMaxSize; this.sendTimeOut = sendTimeOut; this.receiveTimeOut = receiveTimeOut; await Task.Run(() => { this.semaphore = new Semaphore(this.maxConnCount, this.maxConnCount); //设置初始线程数为cpu核数*2 this.connectedEntityList = new ConcurrentDictionary <int, IOCPSocket.SocketUserToken>(Environment.ProcessorCount * 2, this.maxConnCount); //读写分离, 每个socket连接需要2个SocketAsyncEventArgs. saePool = new SocketAsyncEventArgsPool(this.initConnectionResourceCount * 2, SendAndReceiveArgs_Completed, this.singleBufferMaxSize); this.entityPool = new ConcurrentStack <SocketUserToken>(); Parallel.For(0, initConnectionResourceCount, i => { SocketUserToken token = new SocketUserToken(bufferProcess, singleBufferMaxSize); token.ReceiveArgs = saePool.Pop(); token.SendArgs = saePool.Pop(); this.entityPool.Push(token); }); }); }
/// <summary> /// 初始化 SocketUserToken 实例 /// </summary> public SocketUserToken(ISocketBufferProcess bufferProcess, int singleBufferMaxSize) { this.BufferProcess = bufferProcess ?? throw new ArgumentNullException("bufferProcess"); this.bufferManager = BufferManager.CreateBufferManager(2, singleBufferMaxSize); this.Reset(); }