Socket.Connected Propriedade

Definição

Obtém um valor que indica se um Socket está conectado a um host remoto desde a última operação Send ou Receive.Gets a value that indicates whether a Socket is connected to a remote host as of the last Send or Receive operation.

public:
 property bool Connected { bool get(); };
public bool Connected { get; }
member this.Connected : bool
Public ReadOnly Property Connected As Boolean

Valor da propriedade

Boolean

true se o Socket tiver sido conectado a um recurso remoto desde a operação mais recente; caso contrário, false.true if the Socket was connected to a remote resource as of the most recent operation; otherwise, false.

Exemplos

O exemplo de código a seguir se conecta a um ponto de extremidade remoto, verifica a Connected propriedade e verifica o estado atual da conexão.The following code example connects to a remote endpoint, checks the Connected property, and checks the current state of the connection.

client->Connect( anEndPoint );
if (  !client->Connected )
{
   Console::WriteLine( "Winsock error: {0}", Convert::ToString(
      System::Runtime::InteropServices::Marshal::GetLastWin32Error() ) );
}
   
// This is how you can determine whether a socket is still connected.
bool blockingState = client->Blocking;
try
{
   array<Byte>^tmp = gcnew array<Byte>(1);
   client->Blocking = false;
   client->Send( tmp, 0, static_cast<SocketFlags>(0) );
   Console::WriteLine( L"Connected!" );
}
catch ( SocketException^ e ) 
{
   // 10035 == WSAEWOULDBLOCK
   if ( e->NativeErrorCode.Equals( 10035 ) )
   {
      Console::WriteLine( "Connected from an exception!" );
   }
   else
   {
      Console::WriteLine( "Disconnected: {0}!", e->NativeErrorCode );
   }
}
finally
{
   client->Blocking = blockingState;
}

Console::WriteLine( "Connected: {0}", client->Connected );
// .Connect throws an exception if unsuccessful
client.Connect(anEndPoint);

// This is how you can determine whether a socket is still connected.
bool blockingState = client.Blocking;
try
{
    byte [] tmp = new byte[1];

    client.Blocking = false;
    client.Send(tmp, 0, 0);
    Console.WriteLine("Connected!");
}
catch (SocketException e)
{
    // 10035 == WSAEWOULDBLOCK
    if (e.NativeErrorCode.Equals(10035))
    {
        Console.WriteLine("Still Connected, but the Send would block");
    }
    else
    {
        Console.WriteLine("Disconnected: error code {0}!", e.NativeErrorCode);
    }
}
finally
{
    client.Blocking = blockingState;
}

Console.WriteLine("Connected: {0}", client.Connected);
    ' .Connect throws an exception if unsuccessful
    client.Connect(anEndPoint)
    
    ' This is how you can determine whether a socket is still connected.
    Dim blockingState As Boolean = client.Blocking
    Try
        Dim tmp(0) As Byte
        
        client.Blocking = False
        client.Send(tmp, 0, 0)
        Console.WriteLine("Connected!")
    Catch e As SocketException
        ' 10035 == WSAEWOULDBLOCK
        If e.NativeErrorCode.Equals(10035) Then
            Console.WriteLine("Still Connected, but the Send would block")
        Else
            Console.WriteLine("Disconnected: error code {0}!", e.NativeErrorCode)
        End If
    Finally
        client.Blocking = blockingState
    End Try
    
    Console.WriteLine("Connected: {0}", client.Connected)

End Sub

Comentários

A Connected propriedade Obtém o estado de conexão do a Socket partir da última operação de e/s.The Connected property gets the connection state of the Socket as of the last I/O operation. Quando ele retorna false , o Socket was nunca foi conectado ou não está mais conectado.When it returns false, the Socket was either never connected, or is no longer connected. Connected Não é thread-safe; Ele pode retornar true depois que uma operação for anulada quando o Socket estiver desconectado de outro thread.Connected is not thread-safe; it may return true after an operation is aborted when the Socket is disconnected from another thread.

O valor da Connected propriedade reflete o estado da conexão a partir da operação mais recente.The value of the Connected property reflects the state of the connection as of the most recent operation. Se você precisar determinar o estado atual da conexão, faça uma chamada de envio de não bloqueio, de zero byte.If you need to determine the current state of the connection, make a nonblocking, zero-byte Send call. Se a chamada retornar com êxito ou lançar um código de erro WAEWOULDBLOCK (10035), o soquete ainda estará conectado; caso contrário, o soquete não estará mais conectado.If the call returns successfully or throws a WAEWOULDBLOCK error code (10035), then the socket is still connected; otherwise, the socket is no longer connected.

Se você chamar Connect em um soquete UDP (User Datagram Protocol), a Connected propriedade sempre retornará true ; no entanto, essa ação não altera a natureza inerente sem conexão do UDP.If you call Connect on a User Datagram Protocol (UDP) socket, the Connected property always returns true; however, this action does not change the inherent connectionless nature of UDP.

Aplica-se a