在網路上使用資料流Using Streams on the Network

網路資源在 .NET Framework 中是以資料流的形式呈現。Network resources are represented in the .NET Framework as streams. 因為對資料流沒有任何特殊待遇,.NET Framework 提供下列功能:By treating streams generically, the .NET Framework offers the following capabilities:

  • 以一般方式傳送和接收 Web 資料。A common way to send and receive Web data. 不論實際的檔案內容為何 (HTML、XML 或其他格式),應用程式都會使用 Stream.WriteStream.Read 來傳送和接收資料。Whatever the actual contents of the file — HTML, XML, or anything else — your application will use Stream.Write and Stream.Read to send and receive data.

  • 與整個 .NET Framework 資料流的相容性。Compatibility with streams across the .NET Framework. .NET Framework 中無處不使用資料流,其處理資料流的基礎結構健全。Streams are used throughout the .NET Framework, which has a rich infrastructure for handling them. 例如,您可將讀取 FileStream 中 XML 資料的應用程式,修改為讀取 NetworkStream 中的資料,而非僅變更將資料流初始化的幾行程式碼。For example, you can modify an application that reads XML data from a FileStream to read data from a NetworkStream instead by changing only the few lines of code that initialize the stream. NetworkStream 類別與其他資料流最大的不同處,在於 NetworkStream 是不可搜尋的,CanSeek 屬性一律傳回 falseSeekPosition 方法則擲回 NotSupportedExceptionThe major differences between the NetworkStream class and other streams are that NetworkStream is not seekable, the CanSeek property always returns false, and the Seek and Position methods throw a NotSupportedException.

  • 資料送達時的處理。Processing of data as it arrives. 來自網路的資料以資料流方式到達時,應用程式可立即存取該資料,而不必等到整個資料集下載完成後才存取。Streams provide access to data as it arrives from the network, rather than forcing your application to wait for an entire data set to be downloaded.

System.Net.Sockets 命名空間包含 NetworkStream 類別,其可特別實作用於網路資源的 Stream 類別。The System.Net.Sockets namespace contains a NetworkStream class that implements the Stream class specifically for use with network resources. System.Net.Sockets 命名空間中的類別會使用 NetworkStream 類別來代表資料流。Classes in the System.Net.Sockets namespace use the NetworkStream class to represent streams.

若要使用傳回的資料流將資料傳送到網路上,請在 WebRequest 上呼叫 GetRequestStreamTo send data to the network using the returned stream, call GetRequestStream on your WebRequest. WebRequest 會將要求標頭傳送到伺服器;然後,您可以 BeginWrite EndWrite 在傳回的資料流程上呼叫、或方法,以將資料傳送至網路資源 WriteThe WebRequest will send request headers to the server; then you can send data to the network resource by calling the BeginWrite, EndWrite, or Write method on the returned stream. 有些通訊協定 (例如 HTTP) 可能會要求您先設定特定通訊協定屬性,再傳送資料。Some protocols, such as HTTP, may require you to set protocol-specific properties before sending data. 下列程式碼範例示範如何設定用於傳送資料的特定 HTTP 屬性。The following code example shows how to set HTTP-specific properties for sending data. 它假設變數 sendData 包含要傳送的資料,而變數 sendLength 則是要傳送資料的位元組數。It assumes that the variable sendData contains the data to send and that the variable sendLength is the number of bytes of data to send.

HttpWebRequest request =
   (HttpWebRequest) WebRequest.Create("http://www.contoso.com/");  
request.Method = "POST";  
request.ContentLength = sendLength;  
try  
{  
   Stream sendStream = request.GetRequestStream();  
   sendStream.Write(sendData,0,sendLength);  
   sendStream.Close();  
}  
catch  
{  
   // Handle errors . . .  
}  
Dim request As HttpWebRequest = _  
   CType(WebRequest.Create("http://www.contoso.com/"), HttpWebRequest)  
request.Method = "POST"  
request.ContentLength = sendLength  
Try  
   Dim sendStream As Stream = request.GetRequestStream()  
   sendStream.Write(sendData, 0, sendLength)  
   sendStream.Close()  
Catch  
   ' Handle errors . . .  
End Try  

若要從網路接收資料,請在 WebResponse 上呼叫 GetResponseStreamTo receive data from the network, call GetResponseStream on your WebResponse. 然後,您即可在傳回的資料流上呼叫 BeginReadEndReadRead 方法,以讀取網路資源的資料。You can then read data from the network resource by calling the BeginRead, EndRead, or Read method on the returned stream.

使用網路資源的資料流時,請牢記下列要點:When using streams from network resources, keep in mind the following points:

  • 因為 NetworkStream 類別無法在資料流中變更位置,所以 CanSeek 屬性一律傳回 falseThe CanSeek property always returns false since the NetworkStream class cannot change position in the stream. SeekPosition 方法會擲回 NotSupportedExceptionThe Seek and Position methods throw a NotSupportedException.

  • 使用 WebRequestWebResponse 時,呼叫 GetResponseStream 所建立的資料流執行個體為唯讀,而呼叫 GetRequestStream 所建立的資料流執行個體則為唯寫。When you use WebRequest and WebResponse, stream instances created by calling GetResponseStream are read-only and stream instances created by calling GetRequestStream are write-only.

  • 使用 StreamReader 類別可讓編碼工作變得更輕鬆。Use the StreamReader class to make encoding easier. 下列程式碼範例會使用 StreamReaderWebResponse 讀取以 ASCII 編碼的資料流 (範例中未示範如何建立要求)。The following code example uses a StreamReader to read an ASCII-encoded stream from a WebResponse (the example does not show creating the request).

  • 如果沒有可用的網路資源,即可能會封鎖對 GetResponse 的呼叫。The call to GetResponse can block if network resources are not available. 您應考慮透過 BeginGetResponseEndGetResponse 方法使用非同步要求。You should consider using an asynchronous request with the BeginGetResponse and EndGetResponse methods.

  • 完成建立伺服器連線時,可能會封鎖對 GetRequestStream 的呼叫。The call to GetRequestStream can block while the connection to the server is created. 您應考慮透過 BeginGetRequestStreamEndGetRequestStream 方法,對資料流使用非同步要求。You should consider using an asynchronous request for the stream with the BeginGetRequestStream and EndGetRequestStream methods.

// Create a response object.  
WebResponse response = request.GetResponse();  
// Get a readable stream from the server.  
StreamReader sr =
   new StreamReader(response.GetResponseStream(), Encoding.ASCII);  
// Use the stream. Remember when you are through with the stream to close it.  
sr.Close();  
' Create a response object.  
Dim response As WebResponse = request.GetResponse()  
' Get a readable stream from the server.  
Dim sr As _
   New StreamReader(response.GetResponseStream(), Encoding.ASCII)  
' Use the stream. Remember when you are through with the stream to close it.  
sr.Close()  

另請參閱See also