Exemplo n.º 1
0
        /// <summary>
        /// 入栈
        /// </summary>
        /// <param name="item">IOCPClient 实例, 不可为null</param>
        public void Push(IOCPClient item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

            pool.Push(item);
        }
Exemplo n.º 2
0
 /// <summary>
 /// 释放 IOCPClient 资源, 将 IOCPClient 放回池
 /// </summary>
 /// <param name="client">要释放的 IOCPClient</param>
 protected virtual void FreeIOCPClient(IOCPClient client)
 {
     if (client != null)
     {
         connectedClients.TryRemove(client.Id, out IOCPClient _);
         CloseSocket(client.CurrentSocket);
         client.CurrentSocket = null;
         iocpClientPool.Push(client);
         OnClientConnectedStatusChange(this, client.Id, false, null);
         semaphore.Release();
     }
 }
Exemplo n.º 3
0
        /// <summary>
        /// 创建新 IOCPClient
        /// </summary>
        /// <returns></returns>
        private IOCPClient CreateNew()
        {
            IOCPClient result = new IOCPClient();

            result.Id                    = Guid.NewGuid();
            result.ReceiveArgs           = argsPool.Pop();
            result.ReceiveArgs.UserToken = result;
            result.SendArgs              = argsPool.Pop();
            result.SendArgs.UserToken    = result;

            return(result);
        }
Exemplo n.º 4
0
 /// <summary>
 /// 执行 socket 连接异常时的处理
 /// </summary>
 protected virtual void ConnCompletedError(Socket s, SocketError error, IOCPClient client)
 {
     try
     {
         FreeIOCPClient(client);
     }
     catch (Exception ex)
     {
         OnError(this, ex);
     }
     finally
     {
         CloseSocket(s);
     }
 }
Exemplo n.º 5
0
        /// <summary>
        /// 获取一个 IOCPClient 资源
        /// </summary>
        /// <param name="client"></param>
        /// <returns></returns>
        protected virtual bool GetIOCPClient(out IOCPClient client)
        {
            bool result = false;

            client = null;

            //等待10秒,如果有空余资源,接收连接,否则断开socket.
            if (semaphore.WaitOne(10000))
            {
                client = iocpClientPool.Pop();
                client.SocketProtocol = SocketProtocol;
                result = true;
            }

            return(result);
        }
Exemplo n.º 6
0
        /// <summary>
        /// 初始化池
        /// </summary>
        /// <param name="capacity">初始容量</param>
        public IOCPClientPool(int capacity, SocketAsyncEventArgsPool saePool)
        {
            argsPool = saePool ?? throw new ArgumentNullException("saePool");
            pool     = new ConcurrentStack <IOCPClient>();

            for (int i = 0; i < capacity; i++)
            {
                IOCPClient arg = CreateNew();

                if (arg == null)
                {
                    break;
                }

                pool.Push(arg);
            }
        }