TcpClient Classe

Definizione

Vengono fornite connessioni client per i servizi di rete TCP.

public ref class TcpClient : IDisposable
public class TcpClient : IDisposable
type TcpClient = class
    interface IDisposable
Public Class TcpClient
Implements IDisposable
Ereditarietà
TcpClient
Implementazioni

Esempio

Nell'esempio di codice seguente viene stabilita una TcpClient connessione.

void Connect( String^ server, String^ message )
{
   try
   {
      // Create a TcpClient.
      // Note, for this client to work you need to have a TcpServer 
      // connected to the same address as specified by the server, port
      // combination.
      Int32 port = 13000;
      TcpClient^ client = gcnew TcpClient( server,port );
      
      // Translate the passed message into ASCII and store it as a Byte array.
      array<Byte>^data = Text::Encoding::ASCII->GetBytes( message );
      
      // Get a client stream for reading and writing.
      //  Stream stream = client->GetStream();

      NetworkStream^ stream = client->GetStream();
      
      // Send the message to the connected TcpServer. 
      stream->Write( data, 0, data->Length );

      Console::WriteLine( "Sent: {0}", message );
      
      // Receive the TcpServer::response.

      // Buffer to store the response bytes.
      data = gcnew array<Byte>(256);

      // String to store the response ASCII representation.
      String^ responseData = String::Empty;
      
      // Read the first batch of the TcpServer response bytes.
      Int32 bytes = stream->Read( data, 0, data->Length );
      responseData = Text::Encoding::ASCII->GetString( data, 0, bytes );
      Console::WriteLine( "Received: {0}", responseData );
      
      // Close everything.
      client->Close();
   }
   catch ( ArgumentNullException^ e ) 
   {
      Console::WriteLine( "ArgumentNullException: {0}", e );
   }
   catch ( SocketException^ e ) 
   {
      Console::WriteLine( "SocketException: {0}", e );
   }

   Console::WriteLine( "\n Press Enter to continue..." );
   Console::Read();
}
static void Connect(String server, String message)
{
  try
  {
    // Create a TcpClient.
    // Note, for this client to work you need to have a TcpServer
    // connected to the same address as specified by the server, port
    // combination.
    Int32 port = 13000;
    TcpClient client = new TcpClient(server, port);

    // Translate the passed message into ASCII and store it as a Byte array.
    Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);

    // Get a client stream for reading and writing.
   //  Stream stream = client.GetStream();

    NetworkStream stream = client.GetStream();

    // Send the message to the connected TcpServer.
    stream.Write(data, 0, data.Length);

    Console.WriteLine("Sent: {0}", message);

    // Receive the TcpServer.response.

    // Buffer to store the response bytes.
    data = new Byte[256];

    // String to store the response ASCII representation.
    String responseData = String.Empty;

    // Read the first batch of the TcpServer response bytes.
    Int32 bytes = stream.Read(data, 0, data.Length);
    responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
    Console.WriteLine("Received: {0}", responseData);

    // Close everything.
    stream.Close();
    client.Close();
  }
  catch (ArgumentNullException e)
  {
    Console.WriteLine("ArgumentNullException: {0}", e);
  }
  catch (SocketException e)
  {
    Console.WriteLine("SocketException: {0}", e);
  }

  Console.WriteLine("\n Press Enter to continue...");
  Console.Read();
}
Shared Sub Connect(server As [String], message As [String])
   Try
      ' Create a TcpClient.
      ' Note, for this client to work you need to have a TcpServer 
      ' connected to the same address as specified by the server, port
      ' combination.
      Dim port As Int32 = 13000
      Dim client As New TcpClient(server, port)
      
      ' Translate the passed message into ASCII and store it as a Byte array.
      Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(message)
      
      ' Get a client stream for reading and writing.
      '  Stream stream = client.GetStream();
      Dim stream As NetworkStream = client.GetStream()
      
      ' Send the message to the connected TcpServer. 
      stream.Write(data, 0, data.Length)
      
      Console.WriteLine("Sent: {0}", message)
      
      ' Receive the TcpServer.response.
      ' Buffer to store the response bytes.
      data = New [Byte](256) {}
      
      ' String to store the response ASCII representation.
      Dim responseData As [String] = [String].Empty
      
      ' Read the first batch of the TcpServer response bytes.
      Dim bytes As Int32 = stream.Read(data, 0, data.Length)
      responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes)
      Console.WriteLine("Received: {0}", responseData)
      
      ' Close everything.
      stream.Close()
      client.Close()
   Catch e As ArgumentNullException
      Console.WriteLine("ArgumentNullException: {0}", e)
   Catch e As SocketException
      Console.WriteLine("SocketException: {0}", e)
   End Try
   
   Console.WriteLine(ControlChars.Cr + " Press Enter to continue...")
   Console.Read()
End Sub

Commenti

La TcpClient classe fornisce metodi semplici per la connessione, l'invio e la ricezione di dati di flusso tramite una rete in modalità di blocco sincrono.

Per TcpClient connettersi e scambiare dati, è necessario che un TcpListener oggetto o Socket creato con TCP ProtocolType sia in ascolto delle richieste di connessione in ingresso. È possibile connettersi a questo listener in uno dei due modi seguenti:

  • Creare un TcpClient oggetto e chiamare uno dei tre metodi disponibili Connect .

  • Creare un TcpClient oggetto usando il nome host e il numero di porta dell'host remoto. Questo costruttore tenterà automaticamente una connessione.

Nota

Se si desidera inviare datagrammi senza connessione in modalità di blocco sincrono, usare la UdpClient classe .

Note per gli eredi

Per inviare e ricevere dati, usare il GetStream() metodo per ottenere un oggetto NetworkStream. Chiamare i Write(Byte[], Int32, Int32) metodi e Read(Byte[], Int32, Int32) di NetworkStream per inviare e ricevere dati con l'host remoto. Usare il Close(Int32) metodo per rilasciare tutte le risorse associate a TcpClient.

Costruttori

TcpClient()

Inizializza una nuova istanza della classe TcpClient.

TcpClient(AddressFamily)

Inizializza una nuova istanza della classe TcpClient con la famiglia specificata.

TcpClient(IPEndPoint)

Inizializza una nuova istanza della classe TcpClient e la associa all'endpoint locale specificato.

TcpClient(String, Int32)

Inizializza una nuova istanza della classe TcpClient ed effettua la connessione alla porta specificata sull'host specificato.

Proprietà

Active

Ottiene o imposta un valore che indica se è stata stabilita una connessione.

Available

Ottiene la quantità dei dati ricevuti dalla rete e disponibili per essere letti.

Client

Ottiene o imposta l'oggetto Socket sottostante.

Connected

Ottiene un valore che indica se il Socket sottostante di un TcpClient è connesso a un host remoto.

ExclusiveAddressUse

Ottiene o imposta un valore Boolean che specifica se la classe TcpClient consente a un unico client di utilizzare una porta.

LingerState

Ottiene o imposta le informazioni sullo stato di ritardo del socket associato.

NoDelay

Ottiene o imposta un valore che disabilita un ritardo quando i buffer di invio o di ricezione non sono pieni.

ReceiveBufferSize

Ottiene o imposta la dimensione del buffer di ricezione.

ReceiveTimeout

Ottiene o imposta il tempo di attesa di TcpClient prima di ricevere i dati una volta iniziata un'operazione di lettura.

SendBufferSize

Ottiene o imposta la dimensione del buffer di invio.

SendTimeout

Ottiene o imposta il tempo di attesa di TcpClient prima del completamento di un'operazione di invio.

Metodi

BeginConnect(IPAddress, Int32, AsyncCallback, Object)

Avvia una richiesta asincrona di una connessione all'host remoto. L'host remoto viene specificato da un IPAddress e un numero di porta (Int32).

BeginConnect(IPAddress[], Int32, AsyncCallback, Object)

Avvia una richiesta asincrona di una connessione all'host remoto. L'host remoto viene specificato da una matrice di IPAddress e un numero di porta (Int32).

BeginConnect(String, Int32, AsyncCallback, Object)

Avvia una richiesta asincrona di una connessione all'host remoto. L'host remoto viene specificato da un nome host (String) e un numero di porta (Int32).

Close()

Elimina questa istanza di TcpClient e richiede che la connessione TCP sottostante venga chiusa.

Connect(IPAddress, Int32)

Connette il client a un host TCP remoto utilizzando l'endpoint remoto della rete specificato.

Connect(IPAddress[], Int32)

Connette il client a un host TCP remoto utilizzando gli indirizzi IP e il numero di porta specificati.

Connect(IPEndPoint)

Connette il client a un host TCP remoto usando l'endpoint remoto della rete specificato.

Connect(String, Int32)

Connette il client alla porta specificata sull'host specificato.

ConnectAsync(IPAddress, Int32)

Connette il client a un host TCP remoto utilizzando l'indirizzo IP specificato e il numero di porta specificati come operazione asincrona.

ConnectAsync(IPAddress, Int32, CancellationToken)

Connette il client a un host TCP remoto utilizzando l'indirizzo IP specificato e il numero di porta specificati come operazione asincrona.

ConnectAsync(IPAddress[], Int32)

Connette il client a un host TCP remoto utilizzando gli indirizzi IP specificati e il numero di porta specificati come operazione asincrona.

ConnectAsync(IPAddress[], Int32, CancellationToken)

Connette il client a un host TCP remoto utilizzando gli indirizzi IP specificati e il numero di porta specificati come operazione asincrona.

ConnectAsync(IPEndPoint)

Connette il client a un host TCP remoto usando l'endpoint specificato come operazione asincrona.

ConnectAsync(IPEndPoint, CancellationToken)

Connette il client a un host TCP remoto usando l'endpoint specificato come operazione asincrona.

ConnectAsync(String, Int32)

Connette il client alla porta TCP specificata sull'host specificato come operazione asincrona.

ConnectAsync(String, Int32, CancellationToken)

Connette il client alla porta TCP specificata sull'host specificato come operazione asincrona.

Dispose()

Rilascia le risorse gestite e non gestite usate dall'oggetto TcpClient.

Dispose(Boolean)

Rilascia le risorse non gestite usate da TcpClient e, facoltativamente, le risorse gestite.

EndConnect(IAsyncResult)

Termina un tentativo di connessione sincrona in sospeso.

Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.

(Ereditato da Object)
Finalize()

Rilascia le risorse usate dalla classe TcpClient.

GetHashCode()

Funge da funzione hash predefinita.

(Ereditato da Object)
GetStream()

Restituisce il NetworkStream utilizzato per inviare e ricevere dati.

GetType()

Ottiene l'oggetto Type dell'istanza corrente.

(Ereditato da Object)
MemberwiseClone()

Crea una copia superficiale dell'oggetto Object corrente.

(Ereditato da Object)
ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)

Implementazioni dell'interfaccia esplicita

IDisposable.Dispose()

Questa API supporta l'infrastruttura del prodotto e non è previsto che venga usata direttamente dal codice.

Rilascia tutte le risorse usate da TcpClient.

Si applica a

Vedi anche