4

我正在使用TcpClient內置的網絡協議,使用BinaryReader從底層NetworkStream(反過來說,使用BinaryWriter寫入)讀取字節。TcpClient通過NetworkStream傳輸的字節BinaryReader/BinaryWriter

協議以UTF-8編碼傳輸字符串,並呼叫reader.ReadString()從流中讀取它們(使用writer.Write(someStr)進行寫入)。

是否有一種簡單的方法來確定從NetworkStream中讀取(或寫入)的字節數,而不必跳過箍環來計算字符串的實際字節長度?

請注意,BinaryWriter.Write()在字符串的實際字節之前寫入一個7位編碼的整數,這使得任何手動計算都變得更加複雜。

另請注意,NetworkStream不支持Position屬性,因爲它抱怨無法使用Seek

此外,我想避免介紹必須將數據複製/掃描到讀/寫過程中的中介,以免影響整個系統的性能。

是否有簡單,通過網絡接口計數字節的高級方法,而無需手動計算字符串的編碼和長度?

+0

你想做什麼?您可以在網絡流和讀取器之間插入一個自定義流來計算字節數。 – usr

+0

@usr我只需要知道讀取/寫入的總字節數 - 用於報告目的。 *底層協議堆棧中的某些內容必須知道發送/接收的字節數......我想用最少的麻煩來獲取這些信息。 – Optimax

回答

1

您可以在網絡流和讀取器之間插入一個自定義流來計算字節數。

沒有必要複製數據來做到這一點。只需將傳遞的字節數添加到計數器即可。

+0

你能勾畫出一個如何做到這一點的例子嗎? – Optimax

+0

有沒有具體的問題?從Stream中派生並以這種方式包裝另一個流實例。 – usr

+0

不需要涉及緩衝數據嗎?我不想放慢速度。 – Optimax

0

對於那些誰是好奇我是如何實現的字節計數流,在這裏它是在其所有的榮耀(或罵名,視情況而定):

using System; 
using System.IO; 

namespace Streams 
{ 
    /// <summary> 
    /// A wrapper around a <see cref="Stream"/> that keeps track of the number of bytes read and written. 
    /// </summary> 
    public class ByteCountingStream : Stream 
    { 
     private readonly Stream inner; 

     private long totalBytesWritten; 
     private long totalBytesRead; 


     public ByteCountingStream(Stream inner) 
     { 
      this.inner = inner; 
     } 

     public override void Flush() 
     { 
      inner.Flush(); 
     } 

     public override long Seek(long offset, SeekOrigin origin) 
     { 
      throw new NotImplementedException(); 
     } 

     public override void SetLength(long value) 
     { 
      throw new NotImplementedException(); 
     } 

     public override int Read(byte[] buffer, int offset, int count) 
     { 
      int readBytes = inner.Read(buffer, offset, count); 
      totalBytesRead += readBytes; 
      return readBytes; 
     } 

     public override void Write(byte[] buffer, int offset, int count) 
     { 
      inner.Write(buffer, offset, count); 
      totalBytesWritten += count; 
     } 

     public override bool CanRead => true; 
     public override bool CanSeek => false; 
     public override bool CanWrite => true; 

     public override long Length 
     { 
      get 
      { 
       throw new NotImplementedException(); 
      } 
     } 

     public override long Position { get; set; } 

     public long TotalBytesWritten => totalBytesWritten; 
     public long TotalBytesRead => totalBytesRead; 
    } 
} 

的實施通過了緩衝區到底層流,所以確實沒有涉及數據複製。

+1

'長度'看起來破損。這是否總是返回0?應該拋出。 – usr

+0

@us右。固定。 – Optimax

+0

位置也是。我幾乎忽略了新的簡潔的6.0語法。需要習慣那個。另外,我認爲如果沒有處置,這個班就相當危險。 – usr

相關問題