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 동기 차단 모드에서 네트워크를 통해 스트림 데이터를 연결, 전송 및 수신하는 간단한 메서드를 제공합니다.

데이터를 TcpListener 연결하고 교환하려면 TcpClient TCP ProtocolType 를 사용하여 만들거나 Socket 들어오는 연결 요청을 수신 대기해야 합니다. 다음 두 가지 방법 중 하나로 이 수신기에 연결할 수 있습니다.

  • TcpClient 사용 가능한 Connect 세 가지 메서드 중 하나를 만들고 호출합니다.

  • TcpClient 원격 호스트의 호스트 이름 및 포트 번호를 사용하여 만듭니다. 이 생성자는 자동으로 연결을 시도합니다.

참고

동기 차단 모드에서 연결 없는 데이터그램을 보내려면 클래스를 UdpClient 사용합니다.

상속자 참고

데이터를 보내고 받으려면 메서드NetworkStreamGetStream() 사용하여 . 원격 호스트를 사용하여 Write(Byte[], Int32, Int32) Read(Byte[], Int32, Int32) 데이터를 보내고 받을 수 있는 메서드 NetworkStream 및 메서드를 호출합니다. 메서드를 Close(Int32) 사용하여 .와 연결된 모든 리소스를 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에서 사용하는 모든 리소스를 해제합니다.

적용 대상

추가 정보