Search code examples
c#tcparraystcpclient

How to read unknown data length in a TCP Client


I am relativity new to C#. In my TCP client have the following function which sends data to the server and returns the response:

private static TcpClient tcpint = new TcpClient(); //Already initiated and set up
private static NetworkStream stm;                  //Already initiated and set up

private static String send(String data)
{
    //Send data to the server
    ASCIIEncoding asen = new ASCIIEncoding();
    byte[] ba = asen.GetBytes(data);
    stm.Write(ba, 0, ba.Length);

    //Read data from the server
    byte[] bb = new byte[100];
    int k = stm.Read(bb, 0, 100);

    //Construct the response from byte array to string
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < k; i++)
    {
        sb.Append(bb[i].ToString());
    }

    //Return server response
    return sb.ToString();
}

As you can see here, when I am reading the response from the server, I am reading it into a fix byte[] array of length 100 bytes.

byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);

What do i do if the response from the server is more than 100 bytes? How can I read the data without me knowing what the max length of data form the server will be?


Solution

  • Typically, where there is not some specific intrinsic size of something, tcp protocols explicitly send the length of objects they are sending. One possible method for illustration:

    size_t data_len = strlen(some_data_blob);
    char lenstr[32];
    sprintf(lenstr, "%zd\n", data_len);
    send(socket, lenstr, strlen(lenstr));
    send(socket, some_data_blob, data_len);
    

    then when the receiver reads the length string, it knows exactly how mush data should follow (good programming practice is to trust but verify though -- if there is more or less data really sent -- say by an 'evil actor' -- you need to be prepared to handle that).