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

时间:2012-12-17 16:37:48

标签: c# asyncsocket tcp-ip

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

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

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));
}

1 个答案:

答案 0 :(得分:1)

问题在于你是在切断第二个XML文档的开头,而是继续阅读。下一次读取将不会为0,因此您将编写其内容。

Read: XML1
Read: XML1 \0 XML2 <-- you cut this XML2 off
Read: XML2 <-- but then continue reading here.
相关问题