我正在尝试使用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的数据,我希望我假设客户端代码无关紧要,所以我没有发布它。
我确定我做错了什么,但我只是没有看到它。
答案 0 :(得分:1)
您需要检查来自WSARecvFrom
的结果代码并仅在返回代码为GetQueuedCompletionStatus
时调用ERROR_IO_PENDING
- 如果操作未完成而没有阻止且您拥有数据,或者有一个错误,但在任何这些情况下,它都没有发布到I / O完成端口,因此它永远不会被GetQueuedCompletionStatus
接收,并且呼叫将被阻止。
你不应该在一个线程中这样做。常见的方法是让一个线程只轮询I / O完成端口,并调用上下文对象的一些回调来通知传入/传出数据,并在需要的地方调用发送接收调用。