TcpClient.Close 메서드

정의

TcpClient 인스턴스를 삭제하고 내부 TCP 연결을 닫도록 요청합니다.

public:
 void Close();
public void Close ();
member this.Close : unit -> unit
Public Sub Close ()

예제

다음 코드 예제에서는 메서드를 호출하여 닫는 TcpClient 방법을 Close 보여 줍니다.

#using <System.dll>

using namespace System;
using namespace System::Text;
using namespace System::Net;
using namespace System::Net::Sockets;
int main()
{
   
   // Create a client that will connect to a 
   // server listening on the contoso1 computer
   // at port 11000.
   TcpClient^ tcpClient = gcnew TcpClient;
   tcpClient->Connect( "contosoServer", 11000 );
   
   // Get the stream used to read the message sent by the server.
   NetworkStream^ networkStream = tcpClient->GetStream();
   
   // Set a 10 millisecond timeout for reading.
   networkStream->ReadTimeout = 10;
   
   // Read the server message into a byte buffer.
   array<Byte>^bytes = gcnew array<Byte>(1024);
   networkStream->Read( bytes, 0, 1024 );
   
   //Convert the server's message into a string and display it.
   String^ data = Encoding::UTF8->GetString( bytes );
   Console::WriteLine( "Server sent message: {0}", data );
   networkStream->Close();
   tcpClient->Close();
}
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace Examples.System.Net
{
    public class TCPClientExample
    {
        public static void Main()
        {
            // Create a client that will connect to a
            // server listening on the contosoServer computer
            // at port 11000.
            TcpClient tcpClient = new TcpClient();
            tcpClient.Connect("contosoServer", 11000);
            // Get the stream used to read the message sent by the server.
            NetworkStream networkStream = tcpClient.GetStream();
            // Set a 10 millisecond timeout for reading.
            networkStream.ReadTimeout = 10;
            // Read the server message into a byte buffer.
            byte[] bytes = new byte[1024];
            networkStream.Read(bytes, 0, 1024);
            //Convert the server's message into a string and display it.
            string data = Encoding.UTF8.GetString(bytes);
            Console.WriteLine("Server sent message: {0}", data);
            networkStream.Close();
            tcpClient.Close();
        }
    }
}

설명

이 메서드는 Close 인스턴스를 삭제된 것으로 표시하고 연결된 Socket 인스턴스가 TCP 연결을 닫을 것을 요청합니다. 속성에 LingerState 따라 TCP 연결은 데이터를 전송할 때 메서드가 Close 호출된 후 일정 시간 동안 열려 있을 수 있습니다. 기본 연결 닫기를 완료한 경우 알림이 제공되지 않습니다.

이 메서드를 호출하면 결국 연결된 Socket 항목이 닫히게 되며, 생성된 경우 데이터를 보내고 받는 데 사용되는 연결된 NetworkStream 항목도 닫힙니다.

참고

애플리케이션에 네트워크 추적을 사용하도록 설정하면 이 멤버에서 추적 정보를 출력합니다. 자세한 내용은 .NET Framework 네트워크 추적을 참조하세요.

적용 대상