Socket.Select(IList, IList, IList, Int32) Socket.Select(IList, IList, IList, Int32) Socket.Select(IList, IList, IList, Int32) Socket.Select(IList, IList, IList, Int32) Method

Definición

Determina el estado de uno o varios sockets.Determines the status of one or more sockets.

public:
 static void Select(System::Collections::IList ^ checkRead, System::Collections::IList ^ checkWrite, System::Collections::IList ^ checkError, int microSeconds);
public static void Select (System.Collections.IList checkRead, System.Collections.IList checkWrite, System.Collections.IList checkError, int microSeconds);
static member Select : System.Collections.IList * System.Collections.IList * System.Collections.IList * int -> unit
Public Shared Sub Select (checkRead As IList, checkWrite As IList, checkError As IList, microSeconds As Integer)

Parámetros

checkRead
IList IList IList IList

IList de instancias Socket para comprobar la legibilidad.An IList of Socket instances to check for readability.

checkWrite
IList IList IList IList

IList de instancias Socket para comprobar la capacidad de escritura.An IList of Socket instances to check for writability.

checkError
IList IList IList IList

IList de instancias Socket para comprobar errores.An IList of Socket instances to check for errors.

microSeconds
Int32 Int32 Int32 Int32

Valor del tiempo de espera, en microsegundos.The time-out value, in microseconds. Un valor de -1 indica un tiempo de espera infinito.A -1 value indicates an infinite time-out.

Excepciones

El parámetro checkRead es null o está vacío.The checkRead parameter is null or empty.

- y --and- El parámetro checkWrite es null o está vacío.The checkWrite parameter is null or empty - y --and- El parámetro checkError es null o está vacío.The checkError parameter is null or empty.

Error al intentar acceder al socket.An error occurred when attempting to access the socket.

Ejemplos

En el ejemplo de código Select siguiente se usa para determinar qué sockets de escucha tienen una solicitud de conexión.The following code example uses Select to determine which listening sockets have a connection request.

      IPHostEntry^ lipa = Dns::Resolve( Dns::GetHostName() );
      
      //Gets three separate local endpoints.
      IPEndPoint^ lep1 = gcnew IPEndPoint( lipa->AddressList[ 0 ],11000 );
      IPEndPoint^ lep2 = gcnew IPEndPoint( lipa->AddressList[ 0 ],11001 );
      IPEndPoint^ lep3 = gcnew IPEndPoint( lipa->AddressList[ 0 ],11002 );
      
      //creates an array of endpoints.
      array<IPEndPoint^>^ipendpoints = gcnew array<IPEndPoint^>(3);
      ipendpoints[ 0 ] = lep1;
      ipendpoints[ 1 ] = lep2;
      ipendpoints[ 2 ] = lep3;
      
      //Creates three separate sockets.
      Socket^ s1 = gcnew Socket( lep1->Address->AddressFamily,SocketType::Stream,ProtocolType::Tcp );
      Socket^ s2 = gcnew Socket( lep2->Address->AddressFamily,SocketType::Stream,ProtocolType::Tcp );
      Socket^ s3 = gcnew Socket( lep3->Address->AddressFamily,SocketType::Stream,ProtocolType::Tcp );
      array<Socket^>^socketList = gcnew array<Socket^>(3);
      socketList[ 0 ] = s1;
      socketList[ 1 ] = s2;
      socketList[ 2 ] = s3;
      
      //Binds and Listens on all sockets in the array of sockets.
      for ( int i = 0; i < 3; i++ )
      {
         socketList[ i ]->Bind( ipendpoints[ i ] );
         socketList[ i ]->Listen( 1000 );

      }
      
      //Calls Select to determine which sockets are ready for reading.
      Socket::Select( safe_cast<IList^>(socketList), nullptr, nullptr, 1000 );
      
      //Reads on the sockets returned by Select.
      array<Byte>^buffer = gcnew array<Byte>(1024);
      String^ outString;
      for ( Int32 j = 0; j < (socketList->Length - 1); j++ )
      {
         socketList[ j ]->Receive( buffer );
         outString =  "Socket ";
         outString->Concat( j.ToString(),  " has the message", Encoding::ASCII->GetString( buffer ) );
         Console::WriteLine( outString );

      }
   }

};

int main()
{
   return 0;
}

IPHostEntry ipHostEntry = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostEntry.AddressList[0];

Socket socket0 = null;
Socket socket1 = null; 
Socket socket2 = null; 
Socket socket3 = null; 
Socket socket4 = null; 
Socket socket5 = null; 

ArrayList listenList = new ArrayList();
listenList.Add(socket0);
listenList.Add(socket1);
listenList.Add(socket2);

ArrayList acceptList = new ArrayList();
acceptList.Add(socket3);
acceptList.Add(socket4);
acceptList.Add(socket5);

for( int i = 0; i < 3; i++ )
{
  listenList[i] = new Socket(AddressFamily.InterNetwork,
                             SocketType.Stream,
                             ProtocolType.Tcp);
  ((Socket)listenList[i]).Bind(new IPEndPoint(ipAddress, 11000 + i));
  ((Socket)listenList[i]).Listen(10);
}

// Only the sockets that contain a connection request
// will remain in listenList after Select returns.

Socket.Select(listenList, null, null, 1000);

for( int i = 0; i < listenList.Count; i++ )
{
  acceptList[i] = ((Socket)listenList[i]).Accept();
}
Dim ipHostEntry As IPHostEntry = Dns.Resolve(Dns.GetHostName())
Dim ipAddress As IPAddress = ipHostEntry.AddressList(0)

Dim socket0 As Socket = Nothing
Dim socket1 As Socket = Nothing
Dim socket2 As Socket = Nothing
Dim socket3 As Socket = Nothing
Dim socket4 As Socket = Nothing
Dim socket5 As Socket = Nothing

Dim listenList As New ArrayList()
listenList.Add(socket0)
listenList.Add(socket1)
listenList.Add(socket2)

Dim acceptList As New ArrayList()
acceptList.Add(socket3)
acceptList.Add(socket4)
acceptList.Add(socket5)

Dim i As Integer
For i = 0 To 2
   listenList(i) = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
   CType(listenList(i), Socket).Bind(New IPEndPoint(ipAddress, 11000 + i))
   CType(listenList(i), Socket).Listen(10)
Next i

'Only the sockets that contain a connection request
'will remain in listenList after Select returns.
Socket.Select(listenList, Nothing, Nothing, 1000)

For i = 0 To listenList.Count - 1
   acceptList(i) = CType(listenList(i), Socket).Accept()
Next i

Comentarios

Selectes un método estático que determina el estado de una o más Socket instancias de.Select is a static method that determines the status of one or more Socket instances. Debe colocar uno o más Sockets en un IList antes de poder utilizar el Select método.You must place one or more sockets into an IList before you can use the Select method. Compruebe la legibilidad Select llamando a IList con como checkRead parámetro.Check for readability by calling Select with the IList as the checkRead parameter. Para comprobar la escritura de los sockets, utilice el checkWrite parámetro.To check your sockets for writability, use the checkWrite parameter. Para detectar condiciones de error, use checkError.For detecting error conditions, use checkError. Después de Selectllamar a IList , el solo se rellenará con los sockets que cumplan las condiciones.After calling Select, the IList will be filled with only those sockets that satisfy the conditions.

Si está en un estado de escucha, la legibilidad significa que una llamada Accept a se realizará correctamente sin bloqueos.If you are in a listening state, readability means that a call to Accept will succeed without blocking. Si ya ha aceptado la conexión, la legibilidad significa que los datos están disponibles para su lectura.If you have already accepted the connection, readability means that data is available for reading. En estos casos, todas las operaciones de recepción se realizarán correctamente sin bloqueos.In these cases, all receive operations will succeed without blocking. La legibilidad también puede indicar si el Socket control remoto ha cerrado la conexión; en ese caso, una Receive llamada a se devolverá inmediatamente, con cero bytes devueltos.Readability can also indicate whether the remote Socket has shut down the connection; in that case a call to Receive will return immediately, with zero bytes returned.

Selectdevuelve cuando al menos uno de los sockets de interés (los sockets de las checkReadlistas checkWrite, y checkError ) cumple los criterios especificados o se supera microSeconds el parámetro, lo que suceda primero.Select returns when at least one of the sockets of interest (the sockets in the checkRead, checkWrite, and checkError lists) meets its specified criteria, or the microSeconds parameter is exceeded, whichever comes first. Si microSeconds se establece en-1, se especifica un tiempo de espera infinito.Setting microSeconds to -1 specifies an infinite time-out.

Si realiza una llamada de no bloqueo a Connect, la escritura significa que se ha conectado correctamente.If you make a nonblocking call to Connect, writability means that you have connected successfully. Si ya tiene establecida una conexión, la escritura significa que todas las operaciones de envío se realizarán correctamente sin bloqueos.If you already have a connection established, writability means that all send operations will succeed without blocking.

Si ha realizado una llamada sin bloqueo a, el Connectparámetro identifica checkerror los sockets que no se han conectado correctamente.If you have made a non-blocking call to Connect, the checkerror parameter identifies sockets that have not connected successfully.

Nota

Use el Poll método si solo desea determinar el estado de un único Socket.Use the Poll method if you only want to determine the status of a single Socket.

Nota

Este método no puede detectar ciertos tipos de problemas de conexión, como un cable de red roto, o que el host remoto se apagó sin problemas.This method cannot detect certain kinds of connection problems, such as a broken network cable, or that the remote host was shut down ungracefully. Debe intentar enviar o recibir datos para detectar estos tipos de errores.You must attempt to send or receive data to detect these kinds of errors.

Nota

Si recibe un SocketException, utilice la SocketException.ErrorCode propiedad para obtener el código de error específico.If you receive a SocketException, use the SocketException.ErrorCode property to obtain the specific error code. Después de obtener este código, consulte la documentación del código de error de la API de Windows Sockets versión 2 para obtener una descripción detallada del error.After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error.

Se aplica a

Consulte también: