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 )
{
   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 类提供在同步阻止模式下通过网络连接、发送和接收流数据的简单方法。

若要 TcpClient 连接和交换数据, TcpListenerSocket 使用 TCP ProtocolType 创建的数据必须侦听传入连接请求。 可以通过以下两种方式之一连接到此侦听器:

  • TcpClient创建并调用三种可用Connect方法之一。

  • 使用远程主机的主机名和端口号创建一个 TcpClient 。 此构造函数将自动尝试连接。

备注

如果要在同步阻塞模式下发送无连接数据报,请使用 UdpClient 类。

继承者说明

若要发送和接收数据,请使用GetStream()该方法获取 。NetworkStream Write(Byte[], Int32, Int32) Read(Byte[], Int32, Int32)调用远程主机发送和接收数据的方法和方法NetworkStream。 Use the Close(Int32) method to release all resources associated with the 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 占用的非托管资源,还可以另外再释放托管资源。

EndConnect(IAsyncResult)

结束挂起的异步连接尝试。

Equals(Object)

确定指定对象是否等于当前对象。

(继承自 Object)
Finalize()

释放 TcpClient 类使用的资源。

GetHashCode()

作为默认哈希函数。

(继承自 Object)
GetStream()

返回用于发送和接收数据的 NetworkStream

GetType()

获取当前实例的 Type

(继承自 Object)
MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
ToString()

返回表示当前对象的字符串。

(继承自 Object)

显式接口实现

IDisposable.Dispose()

此 API 支持产品基础结构,不能在代码中直接使用。

释放由 TcpClient 使用的所有资源。

适用于

另请参阅