我正在尝试使用Winsock创建一个依赖于IO完成端口的UDP客户端/服务器类,但是我无法获得GetQueuedCompletionStatus()函数以在有新数据可用时返回。这可能是由于我的一些误解,但是有关IOCP的示例/文档(使用UDP而不是TCP)很少。
这是我的服务器类的相关内容,为简洁起见,删除了错误检查:
Server::Server()
{
m_iocp = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
}
void Server::StartReceiving()
{
StopReceiving();
m_iocp = CreateIoCompletionPort((HANDLE)m_receiveSocket, m_iocp, (DWORD)this, 0);
//WSAEVENT event = WSACreateEvent();
//WSAEventSelect(m_receiveSocket, event, FD_ACCEPT | FD_CLOSE);
// Start up worker thread for receiving data
m_receiveThread.reset(new std::thread(&Server::ReceiveWorkerThread, this));
}
void Server::Host(const std::string& port)
{
if (!m_initialized)
Initialize();
addrinfo hints = {};
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = IPPROTO_UDP;
hints.ai_flags = AI_PASSIVE;
// Resolve the server address and port
const char* portStr = port.empty() ? kDefaultPort.c_str() : port.c_str();
int result;
AddressInfo addressInfo = AddressInfo::Create(nullptr, portStr, &hints, result); // Calls getaddrinfo()
m_receiveSocket = WSASocket(addressInfo.GetFamily(), addressInfo.GetSocketType(), addressInfo.GetProtocol(), nullptr, 0, WSA_FLAG_OVERLAPPED);
// Bind receiving socket
result = bind(m_receiveSocket, addressInfo.GetSocketAddress(), addressInfo.GetAddressLength());
StartReceiving();
}
void Server::ReceiveWorkerThread()
{
SOCKADDR_IN senderAddr;
int senderAddrSize = sizeof(senderAddr);
DWORD bytesTransferred = 0;
OVERLAPPED* pOverlapped = nullptr;
WSABUF wsaBuf = { (ULONG)m_buffer.GetWriteBufferSize(), m_buffer.GetWriteBufferPointer() };
DWORD flags = 0;
DWORD bytesReceived;
int result = WSARecvFrom(m_receiveSocket, &wsaBuf, 1, &bytesReceived, &flags, (sockaddr*)&senderAddr, &senderAddrSize, pOverlapped, nullptr);
// Process packets until signaled to exit
while (true)
{
DWORD context = 0;
BOOL success = GetQueuedCompletionStatus(
m_iocp,
&bytesTransferred,
&context,
&pOverlapped,
INFINITE);
wsaBuf.len = (ULONG)m_buffer.GetWriteBufferSize();
wsaBuf.buf = m_buffer.GetWriteBufferPointer();
flags = 0;
result = WSARecvFrom(m_receiveSocket, &wsaBuf, 1, &bytesReceived, &flags, (sockaddr*)&senderAddr, &senderAddrSize, pOverlapped, nullptr);
// Code to process packet would go here
if (m_exiting.load() == true)
break; // Kill worker thread
}
}
当我的客户端将数据发送到服务器时,第一个WSARecvFrom会正确提取数据,但是服务器将阻塞对GetQueuedCompletionStatus的调用,并且即使发送更多数据报,也永远不会返回。我还尝试使用WSAEventSelect(在上面对此进行了注释的代码)将套接字置于非阻塞模式,但是没有区别。
通过阅读this类似的帖子,听起来好像至少需要在套接字上进行一次读取才能触发IOCP,这就是为什么我在主循环之外向WSARecvFrom添加了第一个调用的原因。如果服务器在没有IOCP的情况下接收到数据,那么我希望客户端代码无关紧要,因此我没有发布。
我确定我做错了什么,但我只是没有看到它。
最佳答案
仅当返回码为WSARecvFrom
时,才需要检查GetQueuedCompletionStatus
中的结果代码,并调用ERROR_IO_PENDING
-如果不是没有阻塞就完成了操作并且您有数据,或者有错误,但是在在任何情况下,它都不会发布到I / O完成端口,因此GetQueuedCompletionStatus
永远不会将其拾取,并且该调用将被阻止。
而且您不应该在一个线程中执行此操作。常见的方法是有一个仅轮询I / O完成端口并在上下文对象上调用一些回调以通知传入/传出数据的线程,并在需要时调用发送接收调用。