簡體   English   中英

通過TCPIP客戶端連接異步讀取緩沖區

[英]Reading buffer asynchronously over TCPIP client connection

我寫了一個客戶端,該客戶端通過TCP / IP連接到醫療機器。 那台機器根據內部觸發事件向我發送XML文件。 我必須捕獲這些XML並存儲在文件系統上。 我使用了一個提供異步連接並且可以正常工作的類,除了以下幾件事:當檢查寫入的文件時,我注意到它們包含兩個以空值(編碼為0X00)分隔的xml。 因此,我在緩沖區上放置了一種過濾器,但問題仍然存在。 基本上,當我檢測到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));
}

問題是您要切斷第二個XML文檔的開頭,但隨后繼續閱讀。 下次讀取不會有0,因此您將寫入其內容。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM