TcpClient 類別

定義

提供 TCP 網路服務的用戶端連接。Provides client connections for TCP network services.

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

範例

下列程式碼範例會建立TcpClient連接。The following code example establishes a TcpClient connection.

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

備註

TcpClient類別提供簡單的方法,讓您透過網路以同步封鎖模式來連接、傳送和接收資料流程資料。The TcpClient class provides simple methods for connecting, sending, and receiving stream data over a network in synchronous blocking mode.

為了讓TcpClient連接和交換資料,或Socket使用 TCP TcpListener ProtocolType建立的必須接聽連入連線要求。In order for TcpClient to connect and exchange data, a TcpListener or Socket created with the TCP ProtocolType must be listening for incoming connection requests. 您可以透過下列兩種方式的其中一種連接到此接聽程式:You can connect to this listener in one of the following two ways:

  • 建立並呼叫三個可用Connect方法的其中一個。 TcpClientCreate a TcpClient and call one of the three available Connect methods.

  • TcpClient使用遠端主機的主機名稱和埠號碼來建立。Create a TcpClient using the host name and port number of the remote host. 此函式會自動嘗試連接。This constructor will automatically attempt a connection.

注意

如果您想要以同步封鎖模式傳送不需連線的資料包UdpClient ,請使用類別。If you want to send connectionless datagrams in synchronous blocking mode, use the UdpClient class.

給繼承者的注意事項

若要傳送和接收資料,請GetStream()使用方法來NetworkStream取得。To send and receive data, use the GetStream() method to obtain a NetworkStream. 呼叫的Write(Byte[], Int32, Int32)Read(Byte[], Int32, Int32) 方法NetworkStream ,以使用遠端主機來傳送和接收資料。Call the Write(Byte[], Int32, Int32) and Read(Byte[], Int32, Int32) methods of the NetworkStream to send and receive data with the remote host. 使用方法來釋放與相關聯的TcpClient所有資源。 Close(Int32)Use the Close(Int32) method to release all resources associated with the TcpClient.

建構函式

TcpClient()

初始化 TcpClient 類別的新執行個體。Initializes a new instance of the TcpClient class.

TcpClient(AddressFamily)

使用指定的家族,初始化 TcpClient 類別的新執行個體。Initializes a new instance of the TcpClient class with the specified family.

TcpClient(IPEndPoint)

初始化 TcpClient 類別的新執行個體,並將它繫結至指定的本機端點。Initializes a new instance of the TcpClient class and binds it to the specified local endpoint.

TcpClient(String, Int32)

初始化 TcpClient 類別的新執行個體,並將其連接至指定主機的指定通訊埠。Initializes a new instance of the TcpClient class and connects to the specified port on the specified host.

屬性

Active

取得或設定值,指出是否已建立連線。Gets or sets a value that indicates whether a connection has been made.

Available

取得已從網路接收且可供讀取的資料量。Gets the amount of data that has been received from the network and is available to be read.

Client

取得或設定基礎 SocketGets or sets the underlying Socket.

Connected

取得值,指出 Socket 的基礎 TcpClient 是否已連接至遠端主機。Gets a value indicating whether the underlying Socket for a TcpClient is connected to a remote host.

ExclusiveAddressUse

取得或設定 Boolean 值,指定 TcpClient 是否只允許一個用戶端使用通訊埠。Gets or sets a Boolean value that specifies whether the TcpClient allows only one client to use a port.

LingerState

取得或設定關聯通訊端持續狀態的相關資訊。Gets or sets information about the linger state of the associated socket.

NoDelay

取得或設定數值,在傳送或接收緩衝區未滿時停用延遲。Gets or sets a value that disables a delay when send or receive buffers are not full.

ReceiveBufferSize

取得或設定接收緩衝區的大小。Gets or sets the size of the receive buffer.

ReceiveTimeout

取得或設定時間值,TcpClient 一旦啟始讀取作業後,將據此等待以接收資料。Gets or sets the amount of time a TcpClient will wait to receive data once a read operation is initiated.

SendBufferSize

取得或設定傳送緩衝區的大小。Gets or sets the size of the send buffer.

SendTimeout

取得或設定時間值,TcpClient 將據此等候傳送作業成功完成。Gets or sets the amount of time a TcpClient will wait for a send operation to complete successfully.

方法

BeginConnect(IPAddress, Int32, AsyncCallback, Object)

開始遠端主機連接的非同步要求。Begins an asynchronous request for a remote host connection. 遠端主機是由 IPAddress 和通訊埠編號 (Int32) 指定。The remote host is specified by an IPAddress and a port number (Int32).

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

開始遠端主機連接的非同步要求。Begins an asynchronous request for a remote host connection. 遠端主機是由 IPAddress 陣列和通訊埠編號 (Int32) 指定。The remote host is specified by an IPAddress array and a port number (Int32).

BeginConnect(String, Int32, AsyncCallback, Object)

開始遠端主機連接的非同步要求。Begins an asynchronous request for a remote host connection. 遠端主機是由主機名稱 (String) 和連接埠號碼 (Int32) 指定。The remote host is specified by a host name (String) and a port number (Int32).

Close()

處置此 TcpClient 執行個體,並要求關閉基礎 TCP 連接。Disposes this TcpClient instance and requests that the underlying TCP connection be closed.

Connect(IPAddress, Int32)

使用指定的 IP 位址和通訊埠編號將用戶端連接至遠端 TCP 主機。Connects the client to a remote TCP host using the specified IP address and port number.

Connect(IPAddress[], Int32)

使用指定的 IP 位址和通訊埠編號,將用戶端連接至遠端 TCP 主機。Connects the client to a remote TCP host using the specified IP addresses and port number.

Connect(IPEndPoint)

使用指定的遠端網路端點將用戶端連接至遠端 TCP 主機。Connects the client to a remote TCP host using the specified remote network endpoint.

Connect(String, Int32)

將用戶端連接到所指定主機上的指定連接埠。Connects the client to the specified port on the specified host.

ConnectAsync(IPAddress, Int32)

使用指定的 IP 位址和連接埠號碼,以非同步作業方式將用戶端連接至遠端 TCP 主機。Connects the client to a remote TCP host using the specified IP address and port number as an asynchronous operation.

ConnectAsync(IPAddress[], Int32)

使用指定的 IP 位址和連接埠號碼,以非同步作業方式將用戶端連接至遠端 TCP 主機。Connects the client to a remote TCP host using the specified IP addresses and port number as an asynchronous operation.

ConnectAsync(String, Int32)

以非同步作業的方式將用戶端連接至指定主機上的指定 TCP 連接埠。Connects the client to the specified TCP port on the specified host as an asynchronous operation.

Dispose()

釋放 TcpClient 使用的受控與非受控資源。Releases the managed and unmanaged resources used by the TcpClient.

Dispose(Boolean)

釋放 TcpClient 所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。Releases the unmanaged resources used by the TcpClient and optionally releases the managed resources.

EndConnect(IAsyncResult)

結束擱置的非同步連接嘗試。Ends a pending asynchronous connection attempt.

Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)
Finalize()

釋放 TcpClient 類別所使用的資源。Frees resources used by the TcpClient class.

GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(繼承來源 Object)
GetStream()

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

GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(繼承來源 Object)
ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)

明確介面實作

IDisposable.Dispose()

釋放 TcpClient 所使用的所有資源。Releases all resources used by the TcpClient.

安全性

SocketPermission
建立傳出連線或接受連入要求的許可權。Permission to establish an outgoing connection or accept an incoming request.

適用於

另請參閱