次の方法で共有


TcpClient.Close メソッド

定義

この TcpClient インスタンスを破棄し、基になる TCP 接続を閉じる要求を行います。

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

次のコード例では、Close メソッドを呼び出してTcpClientを閉じる方法を示します。

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プロパティに基づいて、データの送信が継続されたときにClose メソッドが呼び出された後、TCP 接続がしばらく開いたままになる場合があります。 基になる接続が閉じたときに通知は表示されません。

このメソッドを呼び出すと、最終的に関連付けられた Socket が閉じられ、作成された場合にデータの送受信に使用される関連付けられた NetworkStream も閉じられます。

このメンバーは、アプリケーションでネットワーク トレースを有効にすると、トレース情報を出力します。 詳細については、「 .NET Framework のネットワーク トレース」を参照してください。

適用対象