2010-01-20 21 views
1

當我使用的插座/ TcpClient的將文件發送到服務器,如下什麼將是字節[]的大小,接收進入流

 NetworkStream nws = tcpClient.GetStream(); 

     FileStream fs; 

     fs = new FileStream(filename, FileMode.Open, FileAccess.Read); 
     byte[] bytesToSend = new byte[fs.Length]; 
     int numBytesRead = fs.Read(bytesToSend, 0, bytesToSend.Length); 
     nws.Write(bytesToSend, 0, numBytesRead); 

在服務器SISE使用,我有這樣的疑問。

我應該用什麼字節[]大小來讀取流?

謝謝

回答

0

它取決於協議。我會讓大小4k或4096。您應該閱讀,直到Read返回0

1

你不能確定一個流的長度,你所能做的只是讀到最後。您可以首先在流中發送長度,以便服務器知道需要多少。但即使如此,通信錯誤可能會截斷髮送的內容。

0

建議的緩衝區大小是this other question的主題。

但是,這意味着您需要從源流中讀取並在循環中多次寫入目標流,直到您到達源流的末尾。代碼可能是這樣的(最初基於示例代碼爲ZipPackage類)

public static long CopyTo(Stream source, Stream target) 
    { 
    const int bufSize = 8192; 
    byte[] buf = new byte[bufSize]; 

    long totalBytes = 0; 
    int bytesRead = 0; 
    while ((bytesRead = source.Read(buf, 0, bufSize)) > 0) 
    { 
     target.Write(buf, 0, bytesRead); 
     totalBytes += bytesRead; 
    } 
    return totalBytes; 
    } 

在.NET 4.0中,這樣的代碼不再是必要的。只需使用新的Stream.CopyTo方法。

+0

非常感謝你爲這個寶貴的鏈接提供了非常需要的信息。我會處理這些建議。 once agian,Thank you – MilkBottle 2010-01-20 06:10:02

相關問題