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");

注釈

接続指向プロトコルを使用している場合は、このメソッドを使用してソケットを閉じます。 このメソッドは、接続を終了し、 プロパティを Connectedfalse設定します。 ただし、 が の場合 reuseSockettrue、ソケットを再利用できます。

ソケットを閉じる前にすべてのデータが確実に送受信されるようにするには、 メソッドを呼び出す前に を呼び Shutdown 出す Disconnect 必要があります。

を最初に呼び出さずに を呼び出すDisconnectShutdown必要がある場合は、 オプションを DontLingerSocketfalse設定し、0 以外のタイムアウト間隔を指定して、送信送信用にキューに入れたデータが確実に送信されるようにすることができます。 Disconnect 次に、データが送信されるまで、または指定されたタイムアウトが切れるまでブロックします。 を にfalse設定DontLingerし、タイムアウト間隔を 0 に指定した場合は、接続を解放し、Close送信キューに入ったデータを自動的に破棄します。

注意

を受け取った場合は SocketException、 プロパティを SocketException.ErrorCode 使用して特定のエラー コードを取得します。 このコードを取得したら、エラーの詳細な説明については、 Windows ソケット バージョン 2 API エラー コード のドキュメントを参照してください。

Note

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

適用対象