共用方式為


TcpClient.Close 方法

定義

處置此 TcpClient 執行個體,並要求關閉基礎 TCP 連接。

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

範例

下列程式代碼範例示範藉由呼叫 Close 方法來關閉 TcpClient

#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 屬性,在呼叫 方法時,當數據仍要傳送時 Close ,TCP 連線可能會保持開啟一段時間。 當基礎連線完成關閉時,不會提供任何通知。

呼叫這個方法最終會導致關閉相關聯的 Socket ,而且也會關閉用來在建立數據時用來傳送和接收數據的關聯 NetworkStream

注意

在應用程式中啟用網路追蹤時,這個成員會輸出追蹤資訊。 如需詳細資訊,請參閱 .NET Framework 中的網路追蹤

適用於