简体   繁体   English

确定NetworkStream是否已完成读取

[英]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. 该第三方使用本地(回送地址)TCP侦听器来处理请求,并以XML数据进行响应。 There are no size headers sent prior to the XML: the transmission is simply closed with a \\r\\n escape sequence. 在XML之前没有发送大小标头:仅使用\\ r \\ n转义序列关闭传输。 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. 现在,这里的主要问题是,尽管大多数XML数据都已转义,但换行符却没有。 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文档。 XML documents have one root node and when you find the end of the root node your document is complete. XML文档具有一个根节点,当您找到根节点的末尾时,您的文档就完成了。 You can check if your document is well formed by trying to parse your response with XDocument.Parse . 您可以通过尝试使用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. 重复调用XDocument.Parse并不是很有效,但是如果对您的目的足够好,那么您可以执行一个简单的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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