0

I have a TCP socket that I use for RTSP communication. As the data is a mixture of line based textual data and byte sized blocks, I attached a StreamReader to the tcpClient.GetStream(), and call .ReadLine() whenever needed for the textual data.

When I need to read a response body, I have a fixed byte count so I tried using stream.Read() but that blocks, presumably as the StreamReader has already read the data into its own buffer. As that does character encoding, it only reads a fixed number of characters rather than bytes.

Is there any way I can read a fixed number of bytes from the stream without scrapping the StreamReader altogether or hoping that the binary data/content is 7-bit safe (and in turn won't decode as UTF-8)? An alternative is to set the StreamReader's encoding to ASCII but that potentially breaks the rest of the protocol which is defined as UTF-8.

Setup:

this.rtspStream = this.rtspSocket.GetStream();
this.rtspReader = new StreamReader(this.rtspStream, Encoding.UTF8);

Text reading:

string line;
while ((line = this.rtspReader.ReadLine()) != string.Empty) {
    // ...
}

Binary reading:

byte[] responseBody = new byte[contentLength];
this.rtspStream.Read(responseBody, 0, contentLength);
6
  • Can you give an example of the RTSP-formatted data? It surprises me that you have to read by line, instead of there being an integer field that indicates how large the text data is. If that's the case, then I'd suggest reading everything using the Stream, then when you want to break the block of text into lines, either just use String.Split, or else make a MemoryStream over the block of text, and use a StreamReader over that to parse into lines. Apr 2, 2014 at 1:30
  • It's based on HTTP so a single request line and a number of separators, double new line terminated. If there is content (which for most cases will just be UTF-8 SDP data), then there is an explicit byte length in one of the headers as per HTTP. ietf.org/rfc/rfc2326.txt
    – Deanna
    Apr 2, 2014 at 1:31
  • Ok, so, again, could you show what you're trying to do? If it's all lines, then I don't understand why you're also reading bytes. I thought it might be a combination of binary and text. Please give a schematic example. Apr 2, 2014 at 1:33
  • Sorry, I was mid comment update, the content is a fixed byte length. While in most cases it is also textual SDP, it's not guaranteed. Yes, for SDP, I could read lines until I get to where I think the end of the content is, I'd much rather just read "The content".
    – Deanna
    Apr 2, 2014 at 1:35
  • Setting the StreamReader's buffer size to 1 doesn't work as it has an internal minimum of 128 bytes.
    – Deanna
    Apr 5, 2014 at 23:15

2 Answers 2

4

Looking at the StreamReader source, it is not possible to mix the use of the StreamReader and reading of bytes direct from the stream as the StreamReader reads bytes into its internal buffer then decodes all it can into a character buffer available for reading.

Setting the buffer size to 0 doesn't help as it forces this to a minimum of 128 bytes.

For my use, I needed to scrap the StreamReader altogether and replace the ReadLine() with something that will read directly from the stream for parsing myself.

private string ReadLine() {
    // Stringbuilder to insert the read characters in to
    StringBuilder line = new StringBuilder();

    // Create an array to store the maximum number of bytes for a single character
    byte[] bytes = new byte[this.encoding.GetMaxByteCount(1)];
    int byteCount = 0;

    while (true) {
        // Read the first byte
        bytes[0] = (byte)this.rtspStream.ReadByte();
        byteCount = 1;

        // If the encoding says this isn't a full character, read until it does
        while (this.encoding.GetCharCount(bytes, 0, byteCount) == 0) {
            bytes[byteCount++] = (byte)this.rtspStream.ReadByte();
        }

        // Get the unencoded character
        char thisChar = this.encoding.GetChars(bytes, 0, byteCount)[0];

        // Exit if it's a new line (/r/n or /n)
        if (thisChar == '\r') { continue; }
        if (thisChar == '\n') { break; }

        line.Append(thisChar);
    }
    return line.ToString();
}
1
  • 1
    An alternative is to use the BinaryReader class that allows encoded chars to be read, as well as the ability to read a fixed length array of bytes.
    – Deanna
    Apr 6, 2014 at 22:44
1

I presume you've already handled all of the headers, including, possibly, a Content-Length header. I'm assuming that you now want to read the content body, which may or may not be text content.

I think the best you'll be able to do is to read the entire content body in as a stream, then to wrap the content in a StreamReader in the case where the content is text:

List<string> lines = new List<string>();
byte[] responseBody = new byte[contentLength];
this.rtspStream.Read(responseBody, 0, contentLength);
if (contentIsText)
{
    using (var memoryStream = new MemoryStream(responseBody, 0, contentLength))
    {
        using (var reader = new StreamReader(memoryStream))
        {
            string line;
            while ((line = reader.ReadLine()) != string.Empty)
            {
                lines.Add(line);
            }
        }
    }
    // Do something with lines
}
else
{
    // Do something with responseBody
}
1
  • That's not the problem, the issue I'm seeing is that I can not call stream.Read() at all when there is a reader attached, as the reader has already read and buffered any received data. To use stream.Read(), I will need to scrap the StreamReader for the header handling, complicating the rest of the read.
    – Deanna
    Apr 5, 2014 at 22:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.