Windows Network Programming Summary (2)
1. WinsokCet Architecture
2. About ACCEPTEX
When using this function, you want to include the system: mswsock.h, and to link: mswsock.lib. The following statement can be added in the source program, which is automatically linked to Mswsock.lib.
#pragma comment (Lib, "Mswsock.lib")
Below is a sample code using the AcceptEx function:
#define strict
#define_win32_winnt 0x0500 // Windows 2000 or Later
#define Win32_Lean_and_mean
#include
#include
#include
#pragma comment (Lib, "WS2_32.LIB")
#pragma comment (Lib, "Mswsock.lib")
int main ()
{
Const int buffs = 48;
LPFN_ACCEPTEX LPFNACCEPTEX = NULL;
Guid GuidAcceptex = WSAID_ACCEPTEX;
DWORD DWBYTES = 0;
Socket Listensocket = invalid_socket;
Socket Clientsocket = Invalid_socket;
Handle hComport = INVALID_HANDLE_VALUE;
Overlapped il;
Char buf [buffsize];
// init winsock lib ....
Listensocket = WSASOCKET (AF_IPX, SOCK_STREAM, NSPROTO_SPX, NULL, 0, WSA_FLAG_OVERLAPPED);
ClientSocket = WSASocket (AF_IPX, Sock_Stream, NSPROTO_SPX, NULL, 0, WSA_FLAG_OVERLAPPED);
// bind && listen ....
// Associate the listening socket with the completion port
CreateiocompletionPort (Handle) Listensocket, HComport, (U_LONG) 0, 0);
// Get AccpeTex Function
WSAIOCTL (ListenSocket,
SiO_GET_EXTENSION_FUNCTION_POINTER,
& Guidacceptex,
Sizeof (GuidAcceptex),
& lpfnacceptex,
SizeOf (m_workinfo.acceptinfo.lpfnacceptex),
& dwbytes,
NULL,
NULL
);
ZeromeMory (buf, bufsize);
ZeromeMory (& OL, SIZEOF (Overlapped);
// Post accept message
lpfnacceptex (listensocket,
Clientsocket,
BUF,
0,
Sizeof (SockAddr_in) 16,
Sizeof (SockAddr_in) 16,
& dwbytes,
& ol
);
}
It should be noted that when obtaining the AcceptL function pointer through WSAIOCTL, you only need to pass to WSAIOCTL a valid socket, the type of Socket does not affect the acquired AcceptEx function pointer. If you do not want AcceptEx to establish a connection, wait for the user to send data, then set the fourth parameter to 0. The 5th, 6 parameters must be 16 bytes of the size of the address type corresponding to the socket.
In order to make the server better handle the user connection request, the following two strategies can be taken:
A. Set two boundary values to keep the system unprocessed Accept operation at a fixed level. Recommended upper limit is 10;
B. Listen to the FD_ACCEPT event on the ListenSocket through the WSAEventselect function.
When the completion port is closed, if there is still an unprocessed Accepte action, you should close the listEnsocket first, then in the IOCP, handle these Accept operations (for resource release, etc.), remember not to force the ACCEPT operations that are not processed, otherwise it will result Memory leakage.
To prevent malicious users (after establishing the connection, do not send data), set the Listensocket's SO_CONNECT_TIME attribute.
If you want ClientSockets with the same properties as listensocket, you need to call SO_UPDATE_ACCEPT_CONTEXT to the ClientSocket.