Пример #1
0
        /// <summary>
        /// 用预分配的可重用缓冲区和上下文对象初始化服务器.
        /// </summary>
        public void Init()
        {
            // 为所有的I/O操作分配一个大的字节缓冲区.目的是防止内存碎片的产生
            m_bufferManager.InitBuffer();

            // 可重用的SocketAsyncEventArgs,用于重复接受客户端使用
            SocketAsyncEventArgs readWriteEventArg;
            AsyncUserToken       token;

            // 预分配一个 SocketAsyncEventArgs 对象池

            // 预分配SocketAsyncEventArgs读对象池
            for (int i = 0; i < m_numConnections; i++)
            {
                // 预分配一个 可重用的SocketAsyncEventArgs 对象
                //readWriteEventArg = new SocketAsyncEventArgs();
                // 创建token时同时创建了一个和token关联的用于读数据的SocketAsyncEventArgs对象,
                // 并且创建的SocketAsyncEventArgs对象的UserToken属性值为该token
                token = new AsyncUserToken();

                //token.ReadEventArgs = readWriteEventArg;
                //readWriteEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed);
                // 注册一个SocketAsyncEventArgs完成事件
                token.ReadEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>(IO_Completed);

                //readWriteEventArg.UserToken = new AsyncUserToken();

                // 从缓冲区池中分配一个字节缓冲区给 SocketAsyncEventArg 对象
                //m_bufferManager.SetBuffer(readWriteEventArg);
                m_bufferManager.SetBuffer(token.ReadEventArgs);

                //((AsyncUserToken)readWriteEventArg.UserToken).SetReceivedBytes(readWriteEventArg.Buffer, readWriteEventArg.Offset, 0);
                //设定接收缓冲区及偏移量
                token.SetBuffer(token.ReadEventArgs.Buffer, token.ReadEventArgs.Offset, token.ReadEventArgs.Count);

                // 添加一个 SocketAsyncEventArg 到池中
                //m_readPool.Push(readWriteEventArg);
                m_readPool.Push(token.ReadEventArgs);
            }

            // 预分配SocketAsyncEventArgs写对象池
            for (int i = 0; i < m_numConnections; i++)
            {
                // 预分配一个 可重用的SocketAsyncEventArgs 对象
                readWriteEventArg            = new SocketAsyncEventArgs();
                readWriteEventArg.Completed += new EventHandler <SocketAsyncEventArgs>(IO_Completed);
                readWriteEventArg.UserToken  = null;

                // 从缓冲区池中分配一个字节缓冲区给 SocketAsyncEventArg 对象
                m_bufferManager.SetBuffer(readWriteEventArg);

                //readWriteEventArg.SetBuffer(null, 0, 0);

                // 添加一个 SocketAsyncEventArg 到池中
                m_writePool.Push(readWriteEventArg);
            }
        }