Search code examples
c#socketstcpnetworkstream

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:

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