Reputation: 628
I wrote a client which connect to a medical machine over TCP/IP. That machine send me XML files based on internal triggered event. I have to catch those XML and store on filesystem. I used a class which provide asynchronous connection and works fine except for few things: when I check the written files I noticed that they contains two xml separated by a null value (coded as 0X00). So I put a kind of filter on buffer but the problem remains. Basically I have to break my buffer when I detect the end of an XML file.
This is the code that provide async read:
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));
}
Upvotes: 0
Views: 522
Reputation: 29981
The problem is that you're cutting off the start of the second XML document, but then continuing to read. The next read will not have a 0, so you will write its contents.
Read: XML1
Read: XML1 \0 XML2 <-- you cut this XML2 off
Read: XML2 <-- but then continue reading here.
Upvotes: 1