none
WP7 socket底层的缓冲区默认大小是多大? RRS feed

  • 问题

  • socket底层都有一个接收缓冲区和 发送缓冲区,这两个 不知道是不是 同一个缓冲区, 我想问一下,接收缓冲区的默认大小 在WP7上
    OK, please notice me
    2011年9月30日 7:14

答案

  • socket缓冲区属性Buffer以及设置Buffer的方法SetBuffer。

    SocketAsyncEventArgs.Buffer Property is used with the Socket.AcceptAsync, Socket.ConnectAsync, Socket.ReceiveAsync, Socket.ReceiveFromAsync, Socket.ReceiveMessageFromAsync, Socket.SendAsync, and Socket.SendToAsync methods.

    我认为的最佳实践是分别设置发送缓冲区和接收缓冲区,关于缓冲区的大小暂无相关的理论参数可以为您提供,我所使用的缓冲区的大小为MSDN文档中示例中所采用的值。

    // The maximum size of the data buffer to use with the asynchronous socket methods
    const int MAX_BUFFER_SIZE = 2048;

    下面的代码是一个不错的管理缓冲区的类,请参考。

     

    // The operations exposed on the BufferManager class are not thread safe.
    class BufferManager
    {
        int m_numBytes;                 // the total number of bytes controlled by the buffer pool
        byte[] m_buffer;                // the underlying byte array maintained by the Buffer Manager
        Stack<int> m_freeIndexPool;     //
        int m_currentIndex;
        int m_bufferSize;

        public BufferManager(int totalBytes, int bufferSize)
        {
            m_numBytes = totalBytes;
            m_currentIndex = 0;
            m_bufferSize = bufferSize;
            m_freeIndexPool = new Stack<int>();
        }

        // Allocates buffer space used by the buffer pool
        public void InitBuffer()
        {
            // create one big large buffer and divide that
            // out to each SocketAsyncEventArg object
            m_buffer = new byte[m_numBytes];
        }

        // Assigns a buffer from the buffer pool to the
        // specified SocketAsyncEventArgs object
        //
        // <returns>true if the buffer was successfully set, else false</returns>
        public bool SetBuffer(SocketAsyncEventArgs args)
        {

            if (m_freeIndexPool.Count > 0)
            {
                args.SetBuffer(m_buffer, m_freeIndexPool.Pop(), m_bufferSize);
            }
            else
            {
                if ((m_numBytes - m_bufferSize) < m_currentIndex)
                {
                    return false;
                }
                args.SetBuffer(m_buffer, m_currentIndex, m_bufferSize);
                m_currentIndex += m_bufferSize;
            }
            return true;
        }

        // Removes the buffer from a SocketAsyncEventArg object.
        // This frees the buffer back to the buffer pool
        public void FreeBuffer(SocketAsyncEventArgs args)
        {
            m_freeIndexPool.Push(args.Offset);
            args.SetBuffer(null, 0, 0);
        }

    }

     

     


    Cedar
    2011年10月2日 2:53
    版主