jiten
jiten

Reputation: 5264

maximum data read through socket

I have a function to read data from socket.

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;
        }

This function works well when we have to read small data.But When we have to read large data(more than 100000 byte), it only return a part of data. In dubug mode, I have checked that control reach at break when socet.Available = 65536 . So is It maximum limit which we can read or I am doing something wrong?

Upvotes: 1

Views: 310

Answers (1)

C.Evenhuis
C.Evenhuis

Reputation: 26446

The Receive method returns the number of bytes actually received. So just change that bit to:

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

Note that rxBytes may be less than the number of bytes you originally requested. To ensure that you've read exactly that number of bytes, use:

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;
    }
}

I took the liberty of removing the ref from the parameter, as you're only interested in whether the operation had succeeded completely.

Upvotes: 2

Related Questions