简体   繁体   中英

Establish if a NetworkStream has finished reading

I'm partway through a project to integrate with a third-party application. This third-party uses a local (loopback address) TCP listener to process requests, and respond with XML data. There are no size headers sent prior to the XML: the transmission is simply closed with a \\r\\n escape sequence. The following is what I've come up with to handle this:

byte[] buffer = new buffer[DefaultBufferSize];

do
{
    bytesRead = networkStream.Read(buffer, 0, buffer.Length);
    string response = Encoding.UTF8.GetString(buffer, 0, bytesRead);

    if (response.EndsWith("\r\n"))
    {
        isReading = false;
    }
} while (isReading);

Now, the main problem here is that, while most of the XML data is escaped, newlines are not. So, I could potentially read a segment of the data and the last two characters be, purely be chance match the terminating sequence.

Is there any way around this issue, or do I need raise a bug request with the third party?

You are lucky to have an XML document. XML documents have one root node and when you find the end of the root node your document is complete. You can check if your document is well formed by trying to parse your response with XDocument.Parse . If you don't get any exceptions your response contains a well formed document and is thus completely received.

Calling XDocument.Parse repeatedly is not a very efficient, but if it is good enough for your purposes you have a simple implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM