TcpClient 类

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

**命名空间:**System.Net.Sockets
**程序集:**System(在 system.dll 中)

语法

声明
Public Class TcpClient
    Implements IDisposable
用法
Dim instance As TcpClient
public class TcpClient : IDisposable
public ref class TcpClient : IDisposable
public class TcpClient implements IDisposable
public class TcpClient implements IDisposable

备注

TcpClient 类提供了一些简单的方法,用于在同步阻止模式下通过网络来连接、发送和接收流数据。

为使 TcpClient 连接并交换数据,使用 TCP ProtocolType 创建的 TcpListenerSocket 必须侦听是否有传入的连接请求。可以使用下面两种方法之一连接到该侦听器:

  • 创建一个 TcpClient,并调用三个可用的 Connect 方法之一。

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

提示

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

给继承者的说明 要发送和接收数据,请使用 GetStream 方法来获取一个 NetworkStream。调用 NetworkStreamWriteRead 方法与远程主机之间发送和接收数据。使用 Close 方法释放与 TcpClient 关联的所有资源。

示例

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

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
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();
}
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 = (Int32)13000;
        TcpClient client = new TcpClient(server, (int)port);

        // Translate the passed message into ASCII and store
        // it as a Byte array.
        System.Byte data[] = (System.Byte[])
            System.Text.Encoding.get_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((ubyte[])data, 0, data.length);
        Console.WriteLine("Sent: {0}", message);

        // Receive the TcpServer.response.
        // Buffer to store the response bytes.
        data = new System.Byte[256];

        // String to store the response ASCII representation.
        String responseData = "";

        // Read the first batch of the TcpServer response bytes.
        Int32 bytes = (Int32)stream.Read((ubyte[])data, 0, data.length);
        responseData = System.Text.Encoding.get_ASCII().GetString(
            (ubyte[])data, 0, (int)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();
} //Connect

.NET Framework 安全性

继承层次结构

System.Object
  System.Net.Sockets.TcpClient

线程安全

此类型的任何公共静态(Visual Basic 中的 Shared)成员都是线程安全的,但不保证所有实例成员都是线程安全的。

平台

Windows 98、Windows 2000 SP4、Windows CE、Windows Millennium Edition、Windows Mobile for Pocket PC、Windows Mobile for Smartphone、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求

版本信息

.NET Framework

受以下版本支持:2.0、1.1、1.0

.NET Compact Framework

受以下版本支持:2.0、1.0

请参见

参考

TcpClient 成员
System.Net.Sockets 命名空间
TcpListener
NetworkStream 类
Socket 类
ProtocolType 枚举
IPEndPoint 类
Connect
Write
Read

其他资源

TCP/UDP