TcpClient 类

定义

为 TCP 网络服务提供客户端连接。

public ref class TcpClient : IDisposable
public class TcpClient : IDisposable
type TcpClient = class
    interface IDisposable
Public Class TcpClient
Implements IDisposable
继承
TcpClient
实现

示例

下面的代码示例建立连接 TcpClient

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 创建的连接请求必须侦听传入的连接请求。 可以通过以下两种方式之一连接到此侦听器:

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

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

注释

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

继承者说明

若要发送和接收数据,请使用 GetStream() 该方法获取一个 NetworkStreamWrite(Byte[], Int32, Int32) Read(Byte[], Int32, Int32)调用远程主机发送和接收数据的方法和方法NetworkStream使用该方法释放与 <a0/a0> 关联的所有资源。

构造函数

名称 说明
TcpClient()

初始化 TcpClient 类的新实例。

TcpClient(AddressFamily)

使用指定的系列初始化类的新实例 TcpClient

TcpClient(IPEndPoint)

初始化类的新实例 TcpClient ,并将其绑定到指定的本地终结点。

TcpClient(String, Int32)

初始化类的新实例 TcpClient ,并连接到指定主机上的指定端口。

属性

名称 说明
Active

获取或设置一个值,该值指示是否已建立连接。

Available

获取已从网络接收且可供读取的数据量。

Client

获取或设置基础 Socket

Connected

获取一个值,该值指示基础SocketTcpClient是否连接到远程主机。

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, CancellationToken)

使用指定的 IP 地址和端口号作为异步操作将客户端连接到远程 TCP 主机。

ConnectAsync(IPAddress, Int32)

使用指定的 IP 地址和端口号作为异步操作将客户端连接到远程 TCP 主机。

ConnectAsync(IPAddress[], Int32, CancellationToken)

使用指定的 IP 地址和端口号作为异步操作将客户端连接到远程 TCP 主机。

ConnectAsync(IPAddress[], Int32)

使用指定的 IP 地址和端口号作为异步操作将客户端连接到远程 TCP 主机。

ConnectAsync(IPEndPoint, CancellationToken)

使用指定的终结点作为异步操作将客户端连接到远程 TCP 主机。

ConnectAsync(IPEndPoint)

使用指定的终结点作为异步操作将客户端连接到远程 TCP 主机。

ConnectAsync(String, Int32, CancellationToken)

将客户端作为异步操作连接到指定主机上的指定 TCP 端口。

ConnectAsync(String, Int32)

将客户端作为异步操作连接到指定主机上的指定 TCP 端口。

Dispose()

释放由 使用的 托管和非托管资源。

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命令使用的所有资源。

适用于

另请参阅