Andrew Simpson
Andrew Simpson

Reputation: 7324

Too many bytes received on my server socket

I have a listening socket on my UWP device.

This the code for that:

List<byte> requestInBytes = new List<byte>();

using (IInputStream input = args.Socket.InputStream)
{
    byte[] data = new byte[BufferSize];
    IBuffer buffer = data.AsBuffer();
    uint dataRead = BufferSize;
    while (dataRead == BufferSize)
    {
        await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial);
        requestInBytes.AddRange(data);
        dataRead = buffer.Length;
    }
}
var ct = requestInBytes.Count;

The count returned on that is:

630784

On my client Winform desktop I am sending the byte array as follows:

using (TcpClient clientSocket = new TcpClient())
{
    await clientSocket.ConnectAsync(GeneralTags.RASPBERRY_PI_IP_ADDRESS, GeneralTags.RASPBERRY_PI_PORT);
    using (NetworkStream serverStream = clientSocket.GetStream())
    {
        List<byte> requestInBytes = new List<byte>();

        serverStream.Write(byteArray, 0, byteArray.Length);
        serverStream.Flush();
    }
}

The count of what I am sending is:

626840

Why are there more bytes received into my server?

Upvotes: 0

Views: 565

Answers (1)

Andrey Nasonov
Andrey Nasonov

Reputation: 2629

The problem is that you add the entire buffer array data regardless of the actual number of received bytes.

Change the line

requestInBytes.AddRange(data)

to

requestInBytes.AddRange(data.Take(buffer.Length))

Upvotes: 1

Related Questions