猿问

Socket 问题,目标长度数组不够,是怎么回事?怎么修改呢?

这段代码是 获取http 的图片数据,可是总是出现目标 数组程度不够用?

不知道怎么回事?

        /// <summary>
        /// 得到网页原始字节数组
        /// </summary>
        /// <param name="strHost">主机头</param>
        /// <param name="getBytes">Get字符串的字节数组形式</param>
        /// <param name="iTotalCount">接受的字节数</param>
        /// <returns>原始网页字节数组</returns>
        private byte[] GetHtmlOriginByte(string strHost, int port, byte[] getBytes, out int iTotalCount)
        {
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(strHost, port);
            socket.Send(getBytes);
            byte[] buffer = new byte[256];
            
            int iNumber = socket.Receive(buffer, buffer.Length, SocketFlags.None);
            iTotalCount = iNumber;

            byte[] responseBytes = new byte[iTotalCount + iNumber];


            
            
            buffer.CopyTo(responseBytes, 0);
            while (iNumber > 0)
            {
                iNumber = socket.Receive(buffer, buffer.Length, SocketFlags.None);
                if (iTotalCount + iNumber >= responseBytes.Length)
                {
                    //重新生成个更大的数组
                    byte[] temp = new byte[responseBytes.Length * 2];
                    //原数据copy到新数组中
                    responseBytes.CopyTo(temp, 0);
                    buffer.CopyTo(temp, iTotalCount - 1);
                    responseBytes = temp; //引用变更
                }
                else
                {
                    buffer.CopyTo(responseBytes, iTotalCount - 1);
                }
                iTotalCount += iNumber; //索引位置增加
            }
            return responseBytes;
        }
陪伴而非守候
浏览 547回答 2
2回答

隔江千里

"目标数组长度不够"的异常多数是因为 Array.Copy 或 CopyTo 方法 中 要拷贝的数据长度超过了目标数组的长度所致.

郎朗坤

那到底怎么解决的啊。。。~
随时随地看视频慕课网APP
我要回答