TcpClient TcpClient TcpClient TcpClient Class

定義

提供 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
繼承
TcpClientTcpClientTcpClientTcpClient
實作

範例

下列程式碼範例會建立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 'Connect

備註

TcpClient類別提供簡單的方法來連線,傳送,並接收透過同步封鎖模式中的網路進行串流處理資料。The TcpClient class provides simple methods for connecting, sending, and receiving stream data over a network in synchronous blocking mode.

為了讓TcpClient連接並交換資料,TcpListener或是Socket建立 TCPProtocolType必須接聽內送連接要求。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:

  • 建立TcpClient並呼叫其中一個可用的三個Connect方法。Create 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()方法,以取得NetworkStreamTo 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. 使用Close(Int32)方法來釋放相關聯的所有資源TcpClientUse the Close(Int32) method to release all resources associated with the TcpClient.

建構函式

TcpClient() TcpClient() TcpClient() TcpClient()

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

TcpClient(AddressFamily) TcpClient(AddressFamily) TcpClient(AddressFamily) TcpClient(AddressFamily)

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

TcpClient(IPEndPoint) TcpClient(IPEndPoint) TcpClient(IPEndPoint) TcpClient(IPEndPoint)

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

TcpClient(String, Int32) TcpClient(String, Int32) TcpClient(String, Int32) TcpClient(String, Int32)

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

屬性

Active Active Active Active

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

Available Available Available Available

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

Client Client Client Client

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

Connected Connected Connected Connected

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

ExclusiveAddressUse ExclusiveAddressUse ExclusiveAddressUse ExclusiveAddressUse

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

LingerState LingerState LingerState LingerState

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

NoDelay NoDelay NoDelay NoDelay

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

ReceiveBufferSize ReceiveBufferSize ReceiveBufferSize ReceiveBufferSize

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

ReceiveTimeout ReceiveTimeout ReceiveTimeout ReceiveTimeout

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

SendBufferSize SendBufferSize SendBufferSize SendBufferSize

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

SendTimeout SendTimeout SendTimeout 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) BeginConnect(IPAddress, Int32, AsyncCallback, Object) BeginConnect(IPAddress, Int32, AsyncCallback, Object) 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) BeginConnect(IPAddress[], Int32, AsyncCallback, Object) BeginConnect(IPAddress[], Int32, AsyncCallback, Object) 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) BeginConnect(String, Int32, AsyncCallback, Object) BeginConnect(String, Int32, AsyncCallback, Object) 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() Close() Close() Close()

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

Connect(IPAddress, Int32) Connect(IPAddress, Int32) Connect(IPAddress, Int32) Connect(IPAddress, Int32)

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

Connect(IPAddress[], Int32) Connect(IPAddress[], Int32) Connect(IPAddress[], Int32) Connect(IPAddress[], Int32)

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

Connect(IPEndPoint) Connect(IPEndPoint) Connect(IPEndPoint) Connect(IPEndPoint)

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

Connect(String, Int32) Connect(String, Int32) Connect(String, Int32) Connect(String, Int32)

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

ConnectAsync(IPAddress, Int32) ConnectAsync(IPAddress, Int32) ConnectAsync(IPAddress, Int32) 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) ConnectAsync(IPAddress[], Int32) ConnectAsync(IPAddress[], Int32) 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) ConnectAsync(String, Int32) ConnectAsync(String, Int32) ConnectAsync(String, Int32)

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

Dispose() Dispose() Dispose() Dispose()

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

Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

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

EndConnect(IAsyncResult) EndConnect(IAsyncResult) EndConnect(IAsyncResult) EndConnect(IAsyncResult)

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

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

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

(Inherited from Object)
Finalize() Finalize() Finalize() Finalize()

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

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

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

(Inherited from Object)
GetStream() GetStream() GetStream() GetStream()

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

GetType() GetType() GetType() GetType()

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

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

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

(Inherited from Object)
ToString() ToString() ToString() ToString()

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

(Inherited from Object)

明確介面實作

IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose()

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

安全性

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

適用於

另請參閱