我写了一个客户端,它通过TCP/IP连接到一台医疗机器上。该机器根据内部触发事件向我发送XML文件。我必须捕获这些XML并将其存储在文件系统中。我使用了一个提供异步连接的类,它工作得很好,但有几件事除外:当我检查编写的文件时,我注意到它们包含两个由空值(编码为0X00)分隔的xml。所以我在buffer上放了一种过滤器,但问题仍然存在。基本上,当我检测到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));
}发布于 2012-12-18 00:48:14
问题是您切断了第二个XML文档的开头,但随后继续阅读。下一次读取将不会有0,因此您将写入其内容。
Read: XML1
Read: XML1 \0 XML2 <-- you cut this XML2 off
Read: XML2 <-- but then continue reading here.https://stackoverflow.com/questions/13918152
复制相似问题