首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过TCPIP客户端连接异步读取缓冲区

通过TCPIP客户端连接异步读取缓冲区
EN

Stack Overflow用户
提问于 2012-12-18 00:37:48
回答 1查看 510关注 0票数 0

我写了一个客户端,它通过TCP/IP连接到一台医疗机器上。该机器根据内部触发事件向我发送XML文件。我必须捕获这些XML并将其存储在文件系统中。我使用了一个提供异步连接的类,它工作得很好,但有几件事除外:当我检查编写的文件时,我注意到它们包含两个由空值(编码为0X00)分隔的xml。所以我在buffer上放了一种过滤器,但问题仍然存在。基本上,当我检测到XML文件的结尾时,我必须中断我的缓冲区。

这是提供异步读取的代码:

代码语言:javascript
复制
try
{
    NetworkStream networkStream = this.client.GetStream();                
    int read = networkStream.EndRead(asyncResult);

    if (read == 0)
    {
        if (this.Disconnected != null)
            this.Disconnected(this, new EventArgs());
    }

    byte[] buffer = asyncResult.AsyncState as byte[];
    if (buffer != null)
    {
        byte[] data = new byte[read];
        Buffer.BlockCopy(buffer, 0, data, 0, read);
        networkStream.BeginRead(buffer, 0, buffer.Length, this.ClientReadCallback, buffer);
        content.Append(Encoding.UTF8.GetString(buffer.TakeWhile((b, index) => index <= read).Where(b => b != 0x00).ToArray()));

        // Store the file
        string machineId = StoreFile(content.ToString());

        counter++;
        if (this.DataRead != null)
            this.DataRead(this, new DataReadEventArgs(data));
    }
}
catch (Exception ex)
{
    Logger.Log(ex.Message);
    if (this.ClientReadException != null)
        this.ClientReadException(this, new ExceptionEventArgs(ex));
}
EN

回答 1

Stack Overflow用户

发布于 2012-12-18 00:48:14

问题是您切断了第二个XML文档的开头,但随后继续阅读。下一次读取将不会有0,因此您将写入其内容。

代码语言:javascript
复制
Read: XML1
Read: XML1 \0 XML2 <-- you cut this XML2 off
Read: XML2 <-- but then continue reading here.
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13918152

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档