通过套接字读取的最大数据

时间:2016-11-11 13:09:38

标签: c# sockets networking

我有一个从套接字读取数据的功能。

public int getResp(byte[] Buff, ref int rxBytes)//Buff is byte array of length 150000 bytes
        {          
            while (socet.Available < rxBytes)//rxBytes = 150000
            {
                int socketAvaildata = socet.Available;
                Thread.Sleep(1000);
                if (socketAvaildata == socet.Available)
                    break;
            }
            try
            {
                //Thread.Sleep(100);
                rxBytes = socet.Available;           
                if (rxBytes > 0)
                {
                    socet.Receive(Buff, rxBytes, 0);
                    return rxBytes;
                }
            }
            catch (Exception ex) 
            {

            }
            return -1;
        }

当我们必须读取小数据时,此功能很有效。但是当我们必须读取大数据(超过100000字节)时,它只返回一部分数据。在dubug模式下,我在break时检查了控制范围为socet.Available = 65536。 那么我们可以阅读的最大限度还是我做错了什么?

1 个答案:

答案 0 :(得分:2)

Receive方法返回实际接收的字节数。所以只需将该位更改为:

rxBytes = socet.Receive(Buff, rxBytes, 0);
return rxBytes;

请注意,rxBytes可能小于您最初请求的字节数。为确保您已准确读取该字节数,请使用:

public bool TryReadResponse(byte[] buffer, int expectedNumberOfBytes)
{
    try
    {
        int remaining = expectedNumberOfBytes;
        int offset = 0;
        while (remaining > 0)
        {
            int read = socet.Receive(buffer, offset, remaining, SocketFlags.None);
            if (read == 0)
            {
                // other side has closed the connection before sending the requested number of bytes
                return false;
            }

            offset += read;
            remaining -= read;
        }

        return true;
    }
    catch (Exception ex)
    {
        // failure
        return false;
    }
}

我冒昧地从参数中删除ref,因为您只对操作是否已成功完成感兴趣。