Question

I'm reading from an SslStream as follows:

byte[] data = new byte[tcp.ReceiveBufferSize];
int bytesRead = -1;
do {
    bytesRead = stream.Read(data, 0, data.Length);

    using (MemoryStream ms = new MemoryStream(data, 0, bytesRead))
    using (StreamReader rd = new StreamReader(ms))
    {
        string returnData = rd.ReadToEnd();
        sb.Append(returnData);
    }
} while (bytesRead != 0);

It does read from the stream. However, because the actual length of the stream is unknown, the last read just freezes the app. A sample message looks like this:

HTTP/1.1 200 OK
Content-Type: application/json;charset=utf-8
Content-Length: 11534
Server: Jetty(6.1.x)

{long json data here...}

The server returns the length of the content, however it's not the total length of the stream. Is there an efficient way to read this stream successfully?

Was it helpful?

Solution

I just solved the same problem. I have a buffer size = 4096 and in order to prevent the freeze at the last read, we need to check whether the SslStream.Read is less than the buffer size. If true, we break the read loop, otherwise, we continue reading.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top