Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TCP Socket: looping trough buffers

Im working on creating a loop of sending byte data from client to server for bigger data.
The buffer size is of 100 bytes and the message is of 4085 bytes.

The issue is that

CLIENT:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

int bytesSent = 0;
        int bytesLeft = message.Length;
        Debug.WriteLine(bytesLeft);
        int offset = 0;
        byte[] encodedMessage = Encoding.ASCII.GetBytes(message);

        while (bytesLeft > 0)
        {
            
            int curDataSize = Math.Min(bufferSize, bytesLeft);
            offset += curDataSize;
            networkstream.Write(encodedMessage, bytesSent, curDataSize);

            bytesSent += curDataSize;
            bytesLeft -= curDataSize;
        }

SERVER:

byte[] message = new byte[messageSize];


        int bytesRead = 0;
        int bytesLeft = messageSize;

        while (bytesLeft > 0)
        {
            int curDataSize = Math.Min(bufferSize, bytesLeft);
            if (client.Available < curDataSize)
                curDataSize = client.Available; //This saved me

            bytes = networkstream.Read(message, bytesRead, curDataSize);
            string messagestrr = Encoding.ASCII.GetString(message, 0, bytes);
            Debug.WriteLine(messagestrr);
            bytesRead += curDataSize;
            bytesLeft -= curDataSize;
        }

The issue is that it just keeps looping trough the first 100 bytes(aka the buffer).

enter image description here

>Solution :

        bytes = networkstream.Read(message, bytesRead, curDataSize);

You read into message, starting with position bytesRead. This means you append the new data to the message

        string messagestrr = Encoding.ASCII.GetString(message, 0, bytes);
        Debug.WriteLine(messagestrr);

But then you only print out the first bytes of the message, which are not the one actually Read in the previous line except for the first iteration. It likely should be

        string messagestrr = Encoding.ASCII.GetString(message, bytesRead, bytes);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading