Windows Sockets: Usar la clase CAsyncSocketWindows Sockets: Using Class CAsyncSocket
En este artículo se explica cómo usar la clase CAsyncSocket.This article explains how to use class CAsyncSocket. Tenga en cuenta que esta clase encapsula la API de Windows Sockets en un nivel muy bajo.Be aware that this class encapsulates the Windows Sockets API at a very low level. CAsyncSocket
lo usan los programadores que conocen las comunicaciones de red en detalle, pero quieren la comodidad de las devoluciones de llamada para la notificación de eventos de red.CAsyncSocket
is for use by programmers who know network communications in detail but want the convenience of callbacks for notification of network events. En función de esta suposición, este artículo proporciona solo instrucciones básicas.Based on this assumption, this article provides only basic instruction. Probablemente considere la posibilidad CAsyncSocket
de usar si desea que Windows Sockets sea más fácil de tratar con varios protocolos de red en una aplicación MFC pero no desea sacrificar la flexibilidad.You should probably consider using CAsyncSocket
if you want Windows Sockets' ease of dealing with multiple network protocols in an MFC application but do not want to sacrifice flexibility. También podría sentir que puede obtener una mayor eficacia si programa las comunicaciones más directamente que con el modelo de clase más general CSocket
.You might also feel that you can get better efficiency by programming the communications more directly yourself than you could using the more general alternative model of class CSocket
.
CAsyncSocket
se documenta en la referencia de MFC.CAsyncSocket
is documented in the MFC Reference. Visual C++ también proporciona la especificación de Windows Sockets, que se encuentra en el Windows SDK.Visual C++ also supplies the Windows Sockets specification, located in the Windows SDK. Los detalles le quedan.The details are left to you. Visual C++ no proporciona una aplicación de ejemplo para CAsyncSocket
.Visual C++ does not supply a sample application for CAsyncSocket
.
Si no tiene amplios conocimientos sobre las comunicaciones de red y desea una solución sencilla, utilice la clase CSocket con un CArchive
objeto.If you are not highly knowledgeable about network communications and want a simple solution, use class CSocket with a CArchive
object. Consulte Windows Sockets: usar sockets con archivos para obtener más información.See Windows Sockets: Using Sockets with Archives for more information.
En este artículo se describe:This article covers:
Crear y utilizar un
CAsyncSocket
objeto.Creating and using aCAsyncSocket
object.Sus responsabilidades con CAsyncSocket.Your responsibilities with CAsyncSocket.
Crear y usar un objeto CAsyncSocketCreating and Using a CAsyncSocket Object
Para usar CAsyncSocketTo use CAsyncSocket
Construya un objeto CAsyncSocket y utilice el objeto para crear el identificador de socket subyacente.Construct a CAsyncSocket object and use the object to create the underlying SOCKET handle.
La creación de un socket sigue el patrón de MFC de construcción en dos fases.Creation of a socket follows the MFC pattern of two-stage construction.
Por ejemplo:For example:
CAsyncSocket sock; sock.Create( ); // Use the default parameters
o bien-or-
CAsyncSocket* pSocket = new CAsyncSocket; int nPort = 27; pSocket->Create( nPort, SOCK_DGRAM );
El primer constructor anterior crea un
CAsyncSocket
objeto en la pila.The first constructor above creates aCAsyncSocket
object on the stack. El segundo constructor crea unCAsyncSocket
en el montón.The second constructor creates aCAsyncSocket
on the heap. La primera llamada Create anterior usa los parámetros predeterminados para crear un socket de flujo.The first Create call above uses the default parameters to create a stream socket. La segundaCreate
llamada crea un socket de datagrama con un puerto y una dirección especificados.The secondCreate
call creates a datagram socket with a specified port and address. (Puede utilizar cualquierCreate
versión con cualquier método de construcción).(You can use eitherCreate
version with either construction method.)Los parámetros de
Create
son:The parameters toCreate
are:Un "puerto": un entero corto.A "port": a short integer.
Para un socket de servidor, debe especificar un puerto.For a server socket, you must specify a port. Para un socket de cliente, normalmente acepta el valor predeterminado de este parámetro, lo que permite a Windows Sockets seleccionar un puerto.For a client socket, you typically accept the default value for this parameter, which lets Windows Sockets select a port.
Un tipo de socket: SOCK_STREAM (valor predeterminado) o SOCK_DGRAM.A socket type: SOCK_STREAM (the default) or SOCK_DGRAM.
Una "dirección" de socket, como "ftp.microsoft.com" o "128.56.22.8".A socket "address," such as "ftp.microsoft.com" or "128.56.22.8".
Esta es la dirección del Protocolo de Internet (IP) en la red.This is your Internet Protocol (IP) address on the network. Probablemente se basará siempre en el valor predeterminado de este parámetro.You will probably always rely on the default value for this parameter.
Los términos "puerto" y "dirección de socket" se explican en Windows Sockets: puertos y direcciones de socket.The terms "port" and "socket address" are explained in Windows Sockets: Ports and Socket Addresses.
Si el socket es un cliente, conecte el objeto de socket a un socket de servidor mediante CAsyncSocket:: Connect.If the socket is a client, connect the socket object to a server socket, using CAsyncSocket::Connect.
O bien-or-
Si el socket es un servidor, establezca el socket para empezar a escuchar (con CAsyncSocket:: Listen) para los intentos de conexión desde un cliente.If the socket is a server, set the socket to begin listening (with CAsyncSocket::Listen) for connect attempts from a client. Al recibir una solicitud de conexión, se acepta con CAsyncSocket:: Accept.Upon receiving a connection request, accept it with CAsyncSocket::Accept.
Después de aceptar una conexión, puede realizar tareas como la validación de contraseñas.After accepting a connection, you can perform such tasks as validating passwords.
Nota
La
Accept
función miembro toma una referencia a un nuevo objeto vacíoCSocket
como su parámetro.TheAccept
member function takes a reference to a new, emptyCSocket
object as its parameter. Debe construir este objeto antes de llamar aAccept
.You must construct this object before you callAccept
. Si este objeto de socket sale del ámbito, la conexión se cierra.If this socket object goes out of scope, the connection closes. No llame aCreate
para este nuevo objeto de socket.Do not callCreate
for this new socket object. Para obtener un ejemplo, vea el artículo Windows Sockets: secuencia de operaciones.For an example, see the article Windows Sockets: Sequence of Operations.Realice comunicaciones con otros Sockets llamando a las
CAsyncSocket
funciones miembro del objeto que encapsulan las funciones de la API de Windows Sockets.Carry out communications with other sockets by calling theCAsyncSocket
object's member functions that encapsulate the Windows Sockets API functions.Vea la especificación de Windows Sockets y la clase CAsyncSocket en la referencia de MFC.See the Windows Sockets specification and class CAsyncSocket in the MFC Reference.
Destruya el
CAsyncSocket
objeto.Destroy theCAsyncSocket
object.Si creó el objeto de socket en la pila, se llama a su Destructor cuando la función contenedora sale del ámbito.If you created the socket object on the stack, its destructor is called when the containing function goes out of scope. Si creó el objeto de socket en el montón, con el
new
operador, es responsable de usar eldelete
operador para destruir el objeto.If you created the socket object on the heap, using thenew
operator, you are responsible for using thedelete
operator to destroy the object.El destructor llama a la función miembro Close del objeto antes de destruir el objeto.The destructor calls the object's Close member function before destroying the object.
Para obtener un ejemplo de esta secuencia en el código (realmente para un CSocket
objeto), vea Windows Sockets: secuencia de operaciones.For an example of this sequence in code (actually for a CSocket
object), see Windows Sockets: Sequence of Operations.
Sus responsabilidades con CAsyncSocketYour Responsibilities with CAsyncSocket
Cuando se crea un objeto de la clase CAsyncSocket, el objeto encapsula un identificador de socket de Windows y proporciona operaciones en ese controlador.When you create an object of class CAsyncSocket, the object encapsulates a Windows SOCKET handle and supplies operations on that handle. Cuando use CAsyncSocket
, debe tratar todos los problemas que pueda encontrar si usa la API directamente.When you use CAsyncSocket
, you must deal with all the issues you might face if using the API directly. Por ejemplo:For example:
Escenarios de "bloqueo"."Blocking" scenarios.
Diferencias de orden de bytes entre el envío y la recepción de máquinas.Byte order differences between the sending and receiving machines.
Conversión entre cadenas Unicode y juegos de caracteres multibyte (MBCS).Converting between Unicode and multibyte character set (MBCS) strings.
Para obtener definiciones de estos términos e información adicional, vea Windows Sockets: bloqueo, Windows Sockets: ordenación de bytes, Windows Sockets: convertir cadenas.For definitions of these terms and additional information, see Windows Sockets: Blocking, Windows Sockets: Byte Ordering, Windows Sockets: Converting Strings.
A pesar de estos problemas, CAsycnSocket
la clase puede ser la opción adecuada si la aplicación requiere toda la flexibilidad y el control que puede obtener.Despite these issues, class CAsycnSocket
may be the right choice for you if your application requires all the flexibility and control you can get. Si no es así, considere la posibilidad de usar la clase CSocket
en su lugar.If not, you should consider using class CSocket
instead. CSocket
oculta una gran cantidad de detalles: bombea mensajes de Windows durante las llamadas de bloqueo y le proporciona acceso a CArchive
, que administra las diferencias de orden de bytes y la conversión de cadenas.CSocket
hides a lot of detail from you: it pumps Windows messages during blocking calls and gives you access to CArchive
, which manages byte order differences and string conversion for you.
Para más información, consulte:For more information, see:
Windows Sockets: sockets de secuenciasWindows Sockets: Stream Sockets
Windows Sockets: sockets de datagramasWindows Sockets: Datagram Sockets