我正在学习IOCP,并决定根据以下文章编写自己的包装类:
http://www.codeproject.com/Articles/13382/A-simple-application-using-I-O-Completion-Ports-an
我的项目是使用IOCP的C ++ TCP服务器。客户端使用send()和recv()来发送和接收我无法更改的数据(从我已被告知这不应该导致任何问题,但我提到它以防万一)。它还使用socket()(而不是WSASocket())创建一个套接字。 一切似乎都运行正常(CreateIoCompletionPort没有错误,我可以在没有任何错误的情况下向现有的完成端口添加套接字描述符。我已经通过在每个函数之后添加对WSAGetLastError()的调用来检查所有内容)。
(在此之前,请不要注意不一致的编码风格。我喜欢先把东西放在首位,然后再把它清理干净。)
socket_ = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_IP, NULL, 0, WSA_FLAG_OVERLAPPED);
setsockopt(socket_, IPPROTO_IP, SO_DEBUG | TCP_NODELAY, sockopt, 4);
ioctlsocket(socket_, FIONBIO, &ulSockMode_);
sin_.sin_family = AF_INET;
sin_.sin_port = htons((uint16_t)uiPort_));
hAccept_[0] = WSACreateEvent(); //only 1 event, I'm using an array for convenience
if (hAccept_ == WSA_INVALID_EVENT)
{
//this is never executed
}
WSAEventSelect(socket_, hAccept_[0], FD_ACCEPT);
在检测到传入连接后(我使用WSAWaitForMultipleEevents和WSAEnumNetworkEvents工作不会触发任何错误),我使用以下代码接受客户端(这是问题开始的地方):
SOCKET sock_client{ INVALID_SOCKET };
int32_t len_si{ sizeof(SOCKADDR_IN) };
//sock_client = accept(socket_, reinterpret_cast<SOCKADDR*>(pSockAddr), &len_si); // this works fine
//sock_client = sock_client = WSAAccept(socket_, reinterpret_cast<SOCKADDR*>(pSockAddr), &len_si, NULL, 0);//works fine too
char buf[2 * (sizeof(SOCKADDR_IN) + 16)];
WSAOVERLAPPED wsaovl;
uint32_t bytes{ 0 };
BOOL b = AcceptEx(socket_, sock_client, (PVOID)buf, 0, sizeof(SOCKADDR_IN) + 16, sizeof(SOCKADDR_IN) + 16, reinterpret_cast<LPDWORD>(&bytes), &wsaovl); //this fails, returns 0
int32_t test = WSAGetLastError(); // this returns 6 (WSA_INVALID_HANDLE)
我不知道为什么它适用于accept()和WSAAccept(),但它不适用于AcceptEx()。
如果我使用accept(),接受客户端后我需要立即调用WSARecv()。我还没有向客户端发回任何东西,但我读到需要在工作线程中的GetQueuedCompletionStatus()之前调用它:
WSABUF* buf = new WSABUF;
OVERLAPPED* ovl = new OVERLAPPED;
int32_t flags{ 0 };
int32_t bytes{ 0 };
int32_t bytes_recv = WSARecv(client_socket, buf, 1, &flags, &bytes, ovl, NULL); // this returns -1
int32_t err = WSAGetLastError(); // this returns 6 (WSA_INVALID_HANDLE)
由于这不起作用,我的工作线程中的GetQueuedCompletionStatus()例程继续挂起(或者至少,我认为这是原因)
我在做什么有什么不对吗?我从昨天晚上开始一直试图搜索并修复它,我知道这不是很多时间,但我真的不知道我做得不好。
更新: 我已经改变了我为AcceptEx()初始化套接字的方式。
SOCKET sock_client = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_IP, NULL, 0, WSA_FLAG_OVERLAPPED);
和
WSAOVERLAPPED wsaovl = {};
AcceptEx()仍返回false,但WSAGetLastError()返回的错误现在为997(WSA_IO_PENDING)。我不确定I / O操作究竟在等待什么以及如何修复它。
答案 0 :(得分:2)
我认为问题在于,在IOCP套接字模型的方案中,最复杂的部分是“套接字接受”的开始阶段。这就是大多数教程跳过它并开始讨论如何处理send / recv的原因。
如果你想对IOCP有足够的了解,以便你可以实现一个生产软件,那么我给你的建议是研究它直到你完全掌握它(下面的答案是不够的)。我建议的一个文档是“ Microsoft Windows网络编程 - 第2版”的第5章。这本书可能很旧但对IOCP有效。此外,文章“Windows via C/C++: Synchronous and Asynchronous Device I/O”涉及IOCP的某些方面,但没有足够的信息来制作生产软件。
我会尽力解释,但是,我必须警告你,这可能还不够。这就是......
因此,您缺少的部分是“如何在IOCP套接字模型中执行'套接字接受'”。
首先,让我们检查服务器上典型的Winsock(非IOCP)调用序列;
// (1) Create listen socket on server.
WSASocket()
// (2) Bind an address to your listen socket.
bind()
// (3) Associate the listen socket with an event object on FD_ACCEPT event.
WSAEventSelect(,, FD_ACCEPT )
// (4) Put socket in listen state - now, Windows listening for new
// connection requests. If new requests comes, the associated
// event object will be set.
listen()
// (5) Wait on the event object associated on listen socket. This
// will get signaled when a new connection request comes.
WaitForSingleObject() {
// (6) A network activity has occurred. Verify that FD_ACCEPT has
// raised the event object. This also resets the event object
// so WaitForSingleObject() does not loop non-stop.
WSAEnumNetworkEvents()
// (7) Understanding this part is important. The WSAAccept() doesn't
// just accept connection, it first creates a new socket and
// then associates it with the newly accepted connection.
WSAAccept()
}
步骤(7)适用于基于非IOCP的模型。但是,从性能的角度来看 - 套接字创建是昂贵的。它会减慢连接接受过程。
在IOCP模型中,预先为新的传入连接请求创建套接字。即使在连接请求到来之前,不仅预先创建了套接字,它们也与监听套接字相关联。为实现此目的,Microsoft提供了扩展功能。 IOCP模型所需的两个这样的功能是 AcceptEx()&amp; GetAcceptExSockAddrs的()
注意:使用这些扩展函数时,需要在运行时加载它们以避免性能损失。这可以使用 WSAIoctl()来实现。有关进一步阅读,请参阅AcceptEx()的MSDN文档。
警告:可以使用AcceptEx()将新套接字设置为在连接接受过程中接收一些数据。需要禁用此功能,因为它使应用程序容易受到DoS攻击,即发出连接请求但不发送数据。接收应用程序将无限期地等待该套接字。为了避免它只为其'dwReceiveDataLength'参数传递0值。
一种方法是:
// (1) Create IO completion port
CreateIoCompletionPort()
// (2) Have a method that creates worker threads say 'CreateWorkerThreads()'.
// This assign same method (say WorkerThread_Func()) to all worker threads.
// In the WorkerThread_Func() threads are blocked on call to
// GetQueuedCompletionStatus().
CreateWorkerThreads()
// (3) Create listen socket.
WSASocket()
// (4) Associate listen socket to IO Completion Port created earlier.
CreateIoCompletionPort()
// (5) Bind an address to your listen socket.
bind()
// (6) Put socket in listen state - now, Windows listening for new
// connection requests. If a new request comes, GetQueuedCompletionStatus()
// will release a thread.
listen()
// (7) Create sockets in advance and call AcceptEx on each of
// these sockets. If a new connection requests comes
// Windows will pick one of these sockets and associate the
// connection with it.
//
// As an example, below loop will create 1000 sockets.
GUID GuidAcceptEx = WSAID_ACCEPTEX;
DWORD dwBytes;
LPFN_ACCEPTEX lpfnAcceptEx;
// First, load extension method.
int retCode = WSAIoctl(listenSocket,
SIO_GET_EXTENSION_FUNCTION_POINTER,
&GuidAcceptEx,
sizeof(GuidAcceptEx),
&lpfnAcceptEx,
sizeof(lpfnAcceptEx),
&dwBytes,
NULL,
NULL
);
for( /* loop for 1000 times */ ) {
SOCKET preemptiveSocket = WSASocket(, , , , , WSA_FLAG_OVERLAPPED);
lpfnAcceptEx(listenSocket, preemptiveSocket,,,,,,);
}
这实际上准备您的应用程序以IOCP方式接受套接字。当一个新的连接请求到来时,正在等待GetQueuedCompletionStatus()的一个工作线程将被释放,并将指针移交给数据结构。这将具有由lpfnAcceptEx()创建的套接字。 这个过程完成了吗?还没。通过AcceptEx()调用接受的套接字不会继承listenSocket的属性。要做到这一点,你需要打电话;
setsockopt( acceptSocket, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT,
(char*)&listenSocket, sizeof(listenSocket) );
现在,acceptSocket非常适合用于WSASend / WSARecv!
缺少一些东西!我跳过了关于工作线程如何从GetQueuedCompletionStatus()获取acceptedSocket的部分? 答案是,将您的特制结构传递给lpfnAcceptEx()。当GetQueuedCompletionStatus()返回时,它将具有包含您将传递的套接字的数据结构。 如何制作这样的结构?通过创建一个以'WSAOVERLAPPED'作为其第一个成员的结构。您可以在第一个成员之后拥有自己的任何成员。例如,我的结构看起来像;
typedef struct _WSAOVERLAPPEDPLUS
{
WSAOVERLAPPED ProviderOverlapped; // 'WSAOVERLAPPED' has to be the first member.
SOCKET client; // Use this to pass preemptive socket.
SOCKET listenSocket; // Use this to pass the listenSocket.
DWORD dwBytes;
SOCKET_OPERATION operation; // Enum to assist in knowing what socket operation ...
} WSAOVERLAPPEDPLUS, *LPWSAOVERLAPPEDPLUS;
...
typedef enum SOCKET_OPERATION {
UNINITIALIZED_ENUM, // To protect against memory leaks and uninitialized buffers.
OP_ACCEPTEX,
OP_RECEIVE,
OP_SEND
};
...
//
// So the previously mentioned for() loop will become;
//
for( /* loop for 1000 times */ ) {
SOCKET preemptiveSocket = WSASocket(, , , , , WSA_FLAG_OVERLAPPED);
LPWSAOVERLAPPEDPLUS pOl = new WSAOVERLAPPEDPLUS();
// Initialize our "extended" overlapped structure
memset(pOl, 0, sizeof(WSAOVERLAPPEDPLUS));
pOl->operation = OP_ACCEPTEX;
pOl->client = preemptiveSocket;
pOl->listenSocket = listenSocket;
int buflen = (sizeof(SOCKADDR_IN) + 16) * 2;
char* pBuf = new char[buflen];
memset(pBuf, 0, buflen);
m_lpfnAcceptEx(listenSocket,
preemptiveSocket,
pBuf,
0, // Passed 0 to avoid reading data on accept which in turn
// avoids DDoS attack i.e., connection attempt without data will
// cause AcceptEx to wait indefinitely.
sizeof(SOCKADDR_IN) + 16,
sizeof(SOCKADDR_IN) + 16,
&pOl->dwBytes,
&pOl->ProviderOverlapped
);
}
...当GetQueuedCompletionStatus()返回时,在工作线程中;
while (TRUE)
{
bOk = ::GetQueuedCompletionStatus(hCompPort, &bytes_transferred, &completion_key, &pOverlapped, INFINITE);
if (bOk) {
// Process a successfully completed I/O request
if (completion_key == 0) {
// Safe way to extract the customized structure from pointer
// is to use 'CONTAINING_RECORD'. Read more on 'CONTAINING_RECORD'.
WSAOVERLAPPEDPLUS *pOl = CONTAINING_RECORD(pOverlapped, WSAOVERLAPPEDPLUS, ProviderOverlapped);
if (pOl->operation == OP_ACCEPTEX) {
// Before doing any WSASend/WSARecv, inherit the
// listen socket properties by calling 'setsockopt()'
// as explained earlier.
// The listenSocket and the preemptive socket are available
// in the 'pOl->listenSocket' & 'pOl->client', respectively.
}
delete pOl;
}
}
else {
// Handle error ...
}
我希望这能让您了解如何在IOCP中使用AcceptEx()。