次の方法で共有


TcpClient.Close メソッド

定義

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

public:
 void Close();
public void Close();
member this.Close : unit -> unit
Public Sub 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 も閉じます。

Note

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

適用対象