TcpClient.GetStream Método

Definición

Devuelve la NetworkStream usada para enviar y recibir datos.

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

Objeto NetworkStream subyacente.

Excepciones

TcpClient no está conectada a un host remoto.

Ejemplos

En el ejemplo de código siguiente se usa GetStream para obtener el subyacente NetworkStream. Después de obtener , NetworkStreamenvía y recibe mediante sus Write métodos y Read .

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;
}
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

Comentarios

El GetStream método devuelve un NetworkStream objeto que puede usar para enviar y recibir datos. 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.

Primero debe llamar al Connect método o el GetStream método producirá una InvalidOperationExceptionexcepción . Después de haber obtenido , NetworkStreamllame al Write método para enviar datos al host remoto. Llame al Read método para recibir datos que llegan desde el host remoto. Ambos métodos se bloquean hasta que se realiza la operación especificada. Puede evitar el bloqueo en una operación de lectura comprobando la DataAvailable propiedad . Un true valor significa que los datos han llegado desde el host remoto y están disponibles para su lectura. En este caso, Read se garantiza que se complete inmediatamente. Si el host remoto ha apagado su conexión, Read devolverá inmediatamente con cero bytes.

Nota

Si recibe un SocketException, use SocketException.ErrorCode para obtener el código de error específico. 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.

Nota

Este miembro genera información de seguimiento cuando se habilita el seguimiento de red en la aplicación. Para obtener más información, vea Seguimiento de red en .NET Framework.

Se aplica a

Consulte también