TcpClient.GetStream Método

Definición

Devuelve la NetworkStream usada para enviar y recibir datos.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

Devoluciones

NetworkStream

Objeto NetworkStream subyacente.The underlying NetworkStream.

Excepciones

TcpClient no está conectada a un host remoto.The TcpClient is not connected to a remote host.

El TcpClient se ha cerrado.The TcpClient has been closed.

Ejemplos

En el ejemplo de código siguiente GetStream se usa para obtener el subyacente NetworkStream .The following code example uses GetStream to obtain the underlying NetworkStream. Después de obtener NetworkStream , envía y recibe mediante sus Write métodos y Read .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

Comentarios

El GetStream método devuelve un NetworkStream que se puede usar para enviar y recibir datos.The GetStream method returns a NetworkStream that you can use to send and receive data. La NetworkStream clase hereda de la Stream clase, que proporciona una colección enriquecida de métodos y propiedades que se usan para facilitar las comunicaciones de red.The NetworkStream class inherits from the Stream class, which provides a rich collection of methods and properties used to facilitate network communications.

Debe llamar primero al Connect método o el GetStream método producirá una excepción InvalidOperationException .You must call the Connect method first, or the GetStream method will throw an InvalidOperationException. Después de haber obtenido NetworkStream , llame al Write método para enviar datos al host remoto.After you have obtained the NetworkStream, call the Write method to send data to the remote host. Llame al Read método para recibir los datos que llegan del host remoto.Call the Read method to receive data arriving from the remote host. Ambos métodos se bloquean hasta que se realiza la operación especificada.Both of these methods block until the specified operation is performed. Puede evitar el bloqueo en una operación de lectura comprobando la DataAvailable propiedad.You can avoid blocking on a read operation by checking the DataAvailable property. Un true valor significa que los datos llegaron del host remoto y están disponibles para su lectura.A true value means that data has arrived from the remote host and is available for reading. En este caso, Read se garantiza que se completa inmediatamente.In this case, Read is guaranteed to complete immediately. Si el host remoto ha cerrado su conexión, Read devolverá inmediatamente un valor de cero bytes.If the remote host has shutdown its connection, Read will immediately return with zero bytes.

Nota

Si recibe un SocketException , use SocketException.ErrorCode para obtener el código de error específico.If you receive a SocketException, use SocketException.ErrorCode to obtain the specific error code. Después de obtener este código, puede consultar la documentación del código de error de la API de Windows Sockets versión 2 para obtener una descripción detallada del error.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.

Nota

Este miembro genera información de seguimiento cuando se habilita el seguimiento de red en la aplicación.This member outputs trace information when you enable network tracing in your application. Para obtener más información, consulte seguimiento de red en el .NET Framework.For more information, see Network Tracing in the .NET Framework.

Se aplica a

Consulte también