Socket.Disconnect(Boolean) 方法

定義

關閉通訊端連線並允許重複使用通訊端。

public:
 void Disconnect(bool reuseSocket);
public void Disconnect (bool reuseSocket);
member this.Disconnect : bool -> unit
Public Sub Disconnect (reuseSocket As Boolean)

參數

reuseSocket
Boolean

如果這個通訊端可以在關閉目前連線後重複使用,則為 true,否則為 false

例外狀況

Socket物件已關閉。

嘗試存取通訊端時發生錯誤。

範例

下列程式代碼範例會建立同步通訊的套接字,並將某些數據傳送至遠端主機。 然後它會呼叫 Shutdown,以停止傳送和接收活動,以及 Disconnect,以關閉套接字連線。

IPHostEntry^ ipHost = Dns::GetHostEntry( Dns::GetHostName() );
IPAddress^ ipAddr = ipHost->AddressList[ 0 ];
IPEndPoint^ ipEndPoint = gcnew IPEndPoint( ipAddr,11000 );
Socket^ client = gcnew Socket( AddressFamily::InterNetwork,SocketType::Stream,ProtocolType::Tcp );

// Connect the socket to the remote end point.
client->Connect( ipEndPoint );

// Send some data to the remote device.
String^ data = "This is a string of data <EOF>";
array<Byte>^buffer = Encoding::ASCII->GetBytes( data );
int bytesTransferred = client->Send( buffer );

// Write to the console the number of bytes transferred.
Console::WriteLine( "{0} bytes were sent.\n", bytesTransferred );

// Release the socket.
client->Shutdown( SocketShutdown::Both );
client->Disconnect( true );
if ( client->Connected )
      Console::WriteLine( "We're still connnected" );
else
      Console::WriteLine( "We're disconnected" );
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
IPAddress  ipAddr = ipHost.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 11000);

Socket client = new Socket(AddressFamily.InterNetwork,
    SocketType.Stream, ProtocolType.Tcp);

// Connect the socket to the remote end point.
client.Connect(ipEndPoint);

// Send some data to the remote device.
string data = "This is a string of data <EOF>";
byte[] buffer = Encoding.ASCII.GetBytes(data);

int bytesTransferred =  client.Send(buffer);

// Write to the console the number of bytes transferred.
Console.WriteLine("{0} bytes were sent.\n", bytesTransferred);

// Release the socket.
client.Shutdown(SocketShutdown.Both);

client.Disconnect(true);
if (client.Connected)
    Console.WriteLine("We're still connnected");
else
    Console.WriteLine("We're disconnected");

備註

如果您使用連線導向通訊協定,您可以使用這個方法來關閉套接字。 這個方法會結束連線,並將 Connected 屬性設定為 false。 不過,如果 reuseSockettrue,您可以重複使用套接字。

為了確保在關閉套接字之前傳送和接收所有資料,您應該在呼叫 方法之前呼叫 ShutdownDisconnect

如果您需要在沒有第一次呼叫 的情況下呼叫 DisconnectShutdown,您可以將 選項設定 DontLingerSocketfalse ,並指定非零的逾時間隔,以確保傳送已排入傳出傳輸佇列的數據。 Disconnect 然後封鎖直到傳送數據,或直到指定的逾時到期為止。 如果您設定 DontLingerfalse 並指定零逾時間隔,請 Close 釋放連線,並自動捨棄傳出佇列的數據。

注意

如果您收到 SocketException,請使用 SocketException.ErrorCode 屬性來取得特定的錯誤碼。 取得此程式代碼之後,請參閱 Windows Sockets 第 2 版 API 錯誤碼 檔,以取得錯誤的詳細描述。

注意

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

適用於