TcpClient 類別

定義

提供 TCP 網路服務的用戶端連接。

public ref class TcpClient : IDisposable
public class TcpClient : IDisposable
type TcpClient = class
    interface IDisposable
Public Class TcpClient
Implements IDisposable
繼承
TcpClient
實作

範例

下列程式碼範例會 TcpClient 建立連接。

void Connect( String^ server, String^ message )
{
   TcpClient^ client = nullptr;
   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;
      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.
      NetworkStream^ stream = client->GetStream();
      
      // Send the message to the connected TcpServer. 
      stream->Write( data, 0, data->Length );

      Console::WriteLine( "Sent: {0}", message );
      
      // Receive the server 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 );
      
      // Explicit close is not necessary since TcpClient::Dispose() will be
      // called automatically in finally block.
      // stream->Close();
      // client->Close();
   }
   catch ( ArgumentNullException^ e ) 
   {
      Console::WriteLine( "ArgumentNullException: {0}", e );
   }
   catch ( SocketException^ e ) 
   {
      Console::WriteLine( "SocketException: {0}", e );
   }
   finally
   {
      if (client != nullptr)
         delete client;
   }

   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;

    // Prefer a using declaration to ensure the instance is Disposed later.
    using 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.
    NetworkStream stream = client.GetStream();

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

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

    // Receive the server 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);

    // Explicit close is not necessary since TcpClient.Dispose() will be
    // called automatically.
    // 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

      ' Prefer using declaration to ensure the instance is Disposed later.
      Using 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.
         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 server 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)
         
         ' Explicit close is not necessary since TcpClient.Dispose() will be
         ' called automatically.
         ' stream.Close()
         ' client.Close()
      End Using
   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

備註

類別 TcpClient 提供以同步封鎖模式透過網路連線、傳送和接收資料流程資料的簡單方法。

若要連接 TcpClient 和交換資料, TcpListenerSocket 以 TCP ProtocolType 建立的 必須接聽連入連線要求。 您可以使用下列兩種方式之一來連線到此接聽程式:

  • 建立 並呼叫三個可用 Connect 方法的其中一個 TcpClient

  • TcpClient使用遠端主機的主機名稱和埠號碼建立 。 此建構函式會自動嘗試連線。

注意

如果您想要以同步封鎖模式傳送無連接資料包,請使用 UdpClient 類別。

給繼承者的注意事項

若要傳送和接收資料,請使用 GetStream() 方法來取得 NetworkStreamWrite(Byte[], Int32, Int32)呼叫 的 NetworkStreamRead(Byte[], Int32, Int32) 方法,以傳送和接收遠端主機的資料。 Close(Int32)使用 方法來釋放與 相關聯的 TcpClient 所有資源。

建構函式

TcpClient()

初始化 TcpClient 類別的新執行個體。

TcpClient(AddressFamily)

使用指定的家族,初始化 TcpClient 類別的新執行個體。

TcpClient(IPEndPoint)

初始化 TcpClient 類別的新執行個體,並將它繫結至指定的本機端點。

TcpClient(String, Int32)

初始化 TcpClient 類別的新執行個體,並將它連接至指定主機的指定連接埠。

屬性

Active

取得或設定值,指出是否已建立連線。

Available

取得已從網路接收且可供讀取的資料量。

Client

取得或設定基礎 Socket

Connected

取得值,指出 Socket 的基礎 TcpClient 是否已連接至遠端主機。

ExclusiveAddressUse

取得或設定 Boolean 值,指定 TcpClient 是否只允許一個用戶端使用連接埠。

LingerState

取得或設定關聯通訊端延遲狀態的相關資訊。

NoDelay

取得或設定值,在傳送或接收緩衝區未滿時停用延遲。

ReceiveBufferSize

取得或設定接收緩衝區的大小。

ReceiveTimeout

取得或設定時間值,TcpClient 一旦啟始讀取作業後,將據此等待以接收資料。

SendBufferSize

取得或設定傳送緩衝區的大小。

SendTimeout

取得或設定時間值,TcpClient 將據此等候傳送作業成功完成。

方法

BeginConnect(IPAddress, Int32, AsyncCallback, Object)

開始遠端主機連接的非同步要求。 遠端主機是由 IPAddress 和通訊埠編號 (Int32) 指定。

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

開始遠端主機連接的非同步要求。 遠端主機是由 IPAddress 陣列和通訊埠編號 (Int32) 指定。

BeginConnect(String, Int32, AsyncCallback, Object)

開始遠端主機連接的非同步要求。 遠端主機是由主機名稱 (String) 和連接埠號碼 (Int32) 指定。

Close()

處置此 TcpClient 執行個體,並要求關閉基礎 TCP 連接。

Connect(IPAddress, Int32)

使用指定的 IP 位址和連接埠號碼將用戶端連接至遠端 TCP 主機。

Connect(IPAddress[], Int32)

使用指定的 IP 位址和連接埠號碼,將用戶端連接至遠端 TCP 主機。

Connect(IPEndPoint)

使用指定的遠端網路端點將用戶端連接至遠端 TCP 主機。

Connect(String, Int32)

將用戶端連接到所指定主機上的指定連接埠。

ConnectAsync(IPAddress, Int32)

使用指定的 IP 位址和連接埠號碼,以非同步作業方式將用戶端連接至遠端 TCP 主機。

ConnectAsync(IPAddress, Int32, CancellationToken)

使用指定的 IP 位址和連接埠號碼,以非同步作業方式將用戶端連接至遠端 TCP 主機。

ConnectAsync(IPAddress[], Int32)

使用指定的 IP 位址和連接埠號碼,以非同步作業方式將用戶端連接至遠端 TCP 主機。

ConnectAsync(IPAddress[], Int32, CancellationToken)

使用指定的 IP 位址和連接埠號碼,以非同步作業方式將用戶端連接至遠端 TCP 主機。

ConnectAsync(IPEndPoint)

使用指定的端點做為非同步作業,將用戶端連線到遠端 TCP 主機。

ConnectAsync(IPEndPoint, CancellationToken)

使用指定的端點做為非同步作業,將用戶端連線到遠端 TCP 主機。

ConnectAsync(String, Int32)

以非同步作業的方式將用戶端連接至指定主機上的指定 TCP 連接埠。

ConnectAsync(String, Int32, CancellationToken)

以非同步作業的方式將用戶端連接至指定主機上的指定 TCP 連接埠。

Dispose()

釋放 TcpClient 使用的受控與非受控資源。

Dispose(Boolean)

釋放 TcpClient 所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。

EndConnect(IAsyncResult)

結束擱置的非同步連接嘗試。

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
Finalize()

釋放 TcpClient 類別所使用的資源。

GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetStream()

傳回用來傳送和接收資料的 NetworkStream

GetType()

取得目前執行個體的 Type

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
ToString()

傳回代表目前物件的字串。

(繼承來源 Object)

明確介面實作

IDisposable.Dispose()

此 API 支援此產品基礎結構,但無法直接用於程式碼之中。

釋放 TcpClient 所使用的所有資源。

適用於

另請參閱