TcpClient.GetStream 方法

定義

傳回 NetworkStream,用來傳送和接收資料。Returns the NetworkStream used to send and receive data.

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

傳回

基礎 NetworkStreamThe underlying NetworkStream.

例外狀況

TcpClient 未連接至遠端主機。The TcpClient is not connected to a remote host.

TcpClient 已關閉。The TcpClient has been closed.

範例

下列程式碼範例會GetStream使用來取得基礎NetworkStreamThe following code example uses GetStream to obtain the underlying NetworkStream. 取得NetworkStream之後,它會使用其WriteRead方法來傳送和接收。After obtaining the NetworkStream, it sends and receives using its Write and Read methods.

TcpClient^ tcpClient = gcnew TcpClient;

// Uses the GetStream public method to return the NetworkStream.
NetworkStream^ netStream = tcpClient->GetStream();
if ( netStream->CanWrite )
{
   array<Byte>^sendBytes = 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;
}

if ( netStream->CanRead )
{
   
   // Reads NetworkStream into a byte buffer.
   array<Byte>^bytes = gcnew array<Byte>(tcpClient->ReceiveBufferSize);
   
   // Read can return anything from 0 to numBytesToRead. 
   // This method blocks until at least one byte is read.
   netStream->Read( bytes, 0, (int)tcpClient->ReceiveBufferSize );
   
   // Returns the data received from the host to the console.
   String^ returndata = Encoding::UTF8->GetString( bytes );
   Console::WriteLine( "This is what the host returned to you: {0}", 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;
}


TcpClient tcpClient = new TcpClient ();

// Uses the GetStream public method to return the NetworkStream.
NetworkStream netStream = tcpClient.GetStream ();

if (netStream.CanWrite)
{
    Byte[] sendBytes = 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;
}

if (netStream.CanRead)
{
    // Reads NetworkStream into a byte buffer.
    byte[] bytes = new byte[tcpClient.ReceiveBufferSize];

    // Read can return anything from 0 to numBytesToRead. 
    // This method blocks until at least one byte is read.
    netStream.Read (bytes, 0, (int)tcpClient.ReceiveBufferSize);

    // Returns the data received from the host to the console.
    string returndata = Encoding.UTF8.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;
}
netStream.Close();

     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傳送和接收資料。The GetStream method returns a NetworkStream that you can use to send and receive data. NetworkStream類別繼承Stream自類別,它提供了一組豐富的方法和屬性,可用來加速網路通訊。The NetworkStream class inherits from the Stream class, which provides a rich collection of methods and properties used to facilitate network communications.

您必須先呼叫Connect方法, GetStream否則方法會擲InvalidOperationException回。You must call the Connect method first, or the GetStream method will throw an InvalidOperationException. 取得NetworkStream之後,請Write呼叫方法,將資料傳送至遠端主機。After you have obtained the NetworkStream, call the Write method to send data to the remote host. Read呼叫方法,以接收從遠端主機抵達的資料。Call the Read method to receive data arriving from the remote host. 這兩種方法都會封鎖,直到執行指定的作業為止。Both of these methods block until the specified operation is performed. 您可以藉由檢查DataAvailable屬性來避免封鎖讀取操作。You can avoid blocking on a read operation by checking the DataAvailable property. true值表示資料已從遠端主機抵達,而且可供讀取。A true value means that data has arrived from the remote host and is available for reading. 在此情況下Read ,保證會立即完成。In this case, Read is guaranteed to complete immediately. 如果遠端主機已關閉其連接, Read會立即傳回零位元組。If the remote host has shutdown its connection, Read will immediately return with zero bytes.

注意

NetworkStream當您要傳送和接收資料時,必須關閉。You must close the NetworkStream when you are through sending and receiving data. 關閉TcpClient時, NetworkStream不會釋放。Closing TcpClient does not release the NetworkStream.

注意

如果您收到SocketException,請使用SocketException.ErrorCode來取得特定的錯誤碼。If you receive a SocketException, use SocketException.ErrorCode to obtain the specific error code. 取得此程式碼之後,您可以參考Windows socket 第2版 API 錯誤碼檔,以取得錯誤的詳細描述。After you have obtained this code, you can refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error.

注意

在應用程式中啟用網路追蹤時,這個成員會輸出追蹤資訊。This member outputs trace information when you enable network tracing in your application. 如需詳細資訊,請參閱.NET Framework 中的網路追蹤For more information, see Network Tracing in the .NET Framework.

適用於

另請參閱