user3488765
user3488765

Reputation: 443

Reading large packets over Tcp Client

When using TCP client the NetworkStream.read method often doesn't return a totally filled buffer. How can I make it so it blocks further execution until it has written the whole array?

byte[] datagramByteForm = new byte[dgramSizeInt];
int j = dataIOStream.Read(datagramByteForm, 0, datagramByteForm.Length);//read the actual datagram
if (j != datagramByteForm.Length)
{
    throw new Exception("Connection j value: " + j + " expected amount: " + datagramByteForm.Length);
}

Upvotes: 1

Views: 116

Answers (1)

JKamsker
JKamsker

Reputation: 312

Its actually pretty straight forward, you just need to use the provided arguments in the stream.read function. Here is a example(untested):

        TcpClient TCC = new TcpClient("127.0.0.1", 200);
        int cOffset = 0, dgramSizeInt = 5000, j;
        byte[] datagramByteForm = new byte[dgramSizeInt];

        var dataIOStream = TCC.GetStream();

        while (cOffset <= dgramSizeInt)
        {
            j = dataIOStream.Read(datagramByteForm, cOffset, dgramSizeInt-cOffset);
            cOffset += j;
        }

Upvotes: 1

Related Questions