TcpClient.Close メソッド

定義

この TcpClient インスタンスを破棄し、基になる TCP 接続を終了するように要求します。

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

次のコード例では、メソッドを呼び出して a を 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のネットワーク トレース」を参照してください

適用対象