//----------------------------------------
// Initialize Winsock
int iResult = WSAStartup( MAKEWORD(2,2), &wsaData );
if( iResult != NO_ERROR )
printf("Error at WSAStartup\n");
//----------------------------------------
// Create a handle for the completion port
hCompPort = CreateIoCompletionPort( INVALID_HANDLE_VALUE, NULL, (u_long)0, 0 );
//----------------------------------------
// Create a listening socket
ListenSocket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
if (ListenSocket == INVALID_SOCKET) {
printf("Error at socket(): ListenSocket\n");
WSACleanup();
return;
}
//----------------------------------------
// Associate the listening socket with the completion port
CreateIoCompletionPort((HANDLE)ListenSocket, hCompPort, (u_long)0, 0);
//----------------------------------------
// Bind the listening socket to the local IP address
// and port 27015
hostent* thisHost;
char* ip;
u_short port;
port = 27015;
thisHost = gethostbyname("");
ip = inet_ntoa (*(struct in_addr *)*thisHost->h_addr_list);
//----------------------------------------
// Start listening on the listening socket
if (listen( ListenSocket, 100 ) == SOCKET_ERROR) {
printf("error listening\n");
}
printf("Listening on address: %s:%d\n", ip, port);
//----------------------------------------
// Load the AcceptEx function into memory using WSAIoctl.
// The WSAIoctl function is an extension of the ioctlsocket()
// function that can use overlapped I/O. The function's 3rd
// through 6th parameters are input and output buffers where
// we pass the pointer to our AcceptEx function. This is used
// so that we can call the AcceptEx function directly, rather
// than refer to the Mswsock.lib library.
WSAIoctl(ListenSocket,
SIO_GET_EXTENSION_FUNCTION_POINTER,
&GuidAcceptEx,
sizeof(GuidAcceptEx),
&lpfnAcceptEx,
sizeof(lpfnAcceptEx),
&dwBytes,
NULL,
NULL);
//----------------------------------------
// Associate the accept socket with the completion port
CreateIoCompletionPort((HANDLE)AcceptSocket, hCompPort, (u_long)0, 0);
//----------------------------------------
// Continue on to use send, recv, TransmitFile(), etc.,.
...
针对AcceptEx function [Winsock],我们一般不提倡使用,它是Windows独有的,并不是socket的标准调用,微软在它的MSDN中确实说过,在WIN32中使用AcceptEx 要比accept 相对要快,但在每次该使用它之前,必须调用GetAcceptExSockaddrs来做初始化工作(包括data, local socket address, and remote socket address),调用需要Windows Sockets 2支持,使用起来相当麻烦,尤其是在管理大量使用socket时,你不得不走很多弯路,其效率未必就比标准调用高。如果你真的坚持要用这些,等到做了很多工作后,说不定回头你会发现还不如一开始就用标准的系统调用,特别是兼容POSIX标准,当开发到一定程度,在考虑到程序移植工作时,就更显显出标准使用的必要性。
AcceptEx 详细请参考:
ms-help://MS.MSDNQTR.2004OCT.1033/winsock/winsock/acceptex_2.htm
Requirements系统需求
Client: Requires Windows XP, Windows 2000 Professional, or Windows NT Workstation 3.51 and later.
Server: Requires Windows Server 2003, Windows 2000 Server, or Windows NT Server 3.51 and later.
Header: Declared in Mswsock.h.
Library: Use Mswsock.lib.