TcpClient.GetStream 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
傳回用來傳送和接收資料的 NetworkStream。
public:
System::Net::Sockets::NetworkStream ^ GetStream();
public System.Net.Sockets.NetworkStream GetStream();
member this.GetStream : unit -> System.Net.Sockets.NetworkStream
Public Function GetStream () As NetworkStream
傳回
基礎 NetworkStream。
例外狀況
TcpClient 未連接至遠端主機。
範例
下列程式代碼範例會使用 GetStream 來取得基礎 NetworkStream。 取得 NetworkStream之後,它會使用 其 Write 和 Read 方法來傳送和接收。
using TcpClient tcpClient = new TcpClient();
tcpClient.ConnectAsync("contoso.com", 5000);
using NetworkStream netStream = tcpClient.GetStream();
// Send some data to the peer.
byte[] sendBuffer = Encoding.UTF8.GetBytes("Is anybody there?");
netStream.Write(sendBuffer);
// Receive some data from the peer.
byte[] receiveBuffer = new byte[1024];
int bytesReceived = netStream.Read(receiveBuffer);
string data = Encoding.UTF8.GetString(receiveBuffer.AsSpan(0, bytesReceived));
Console.WriteLine($"This is what the peer sent to you: {data}");
Dim tcpClient As New TcpClient()
' Uses the GetStream public method to return the NetworkStream.
Dim netStream As NetworkStream = tcpClient.GetStream()
If netStream.CanWrite Then
Dim sendBytes As [Byte]() = Encoding.UTF8.GetBytes("Is anybody there?")
netStream.Write(sendBytes, 0, sendBytes.Length)
Else
Console.WriteLine("You cannot write data to this stream.")
tcpClient.Close()
' Closing the tcpClient instance does not close the network stream.
netStream.Close()
Return
End If
If netStream.CanRead Then
' Reads the NetworkStream into a byte buffer.
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
' Read can return anything from 0 to numBytesToRead.
' This method blocks until at least one byte is read.
netStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
' Returns the data received from the host to the console.
Dim returndata As String = Encoding.ASCII.GetString(bytes)
Console.WriteLine(("This is what the host returned to you: " + returndata))
Else
Console.WriteLine("You cannot read data from this stream.")
tcpClient.Close()
' Closing the tcpClient instance does not close the network stream.
netStream.Close()
Return
End If
' Uses the Close public method to close the network stream and socket.
tcpClient.Close()
End Sub
備註
方法 GetStream 會傳 NetworkStream 回可用來傳送和接收資料的 。 類別 NetworkStream 繼承自 Stream 類別,其提供豐富的方法和屬性集合,用來協助網路通訊。
您必須先呼叫 Connect 方法,否則 GetStream 方法會擲回 InvalidOperationException。 取得 NetworkStream之後,請呼叫 Write 方法,將數據傳送至遠端主機。
Read呼叫 方法來接收從遠端主機抵達的數據。 這兩種方法都會封鎖,直到執行指定的作業為止。 您可以藉由檢查 DataAvailable 屬性來避免封鎖讀取作業。 值 true 表示數據已從遠端主機抵達,而且可供讀取。 在此情況下, Read 保證會立即完成。 如果遠端主機已關閉其連線, Read 將會立即以零個字節傳回。
注意
如果您收到 SocketException,請使用 SocketException.ErrorCode 來取得特定的錯誤碼。 取得此程式代碼之後,您可以參閱 Windows Sockets 第 2 版 API 錯誤碼 檔,以取得錯誤的詳細描述。
注意
在應用程式中啟用網路追蹤時,這個成員會輸出追蹤資訊。 如需詳細資訊,請參閱 .NET Framework 中的網路追蹤。