我正在编写一个使用 IO 完成端口的多线程客户端。
我创建并连接了设置了 WSA_FLAG_OVERLAPPED 属性的套接字。
if ((m_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
{
throw std::exception("Failed to create socket.");
}
if (WSAConnectByName(m_socket, L"server.com", L"80", &localAddressLength, reinterpret_cast<sockaddr*>(&localAddress), &remoteAddressLength, &remoteAddress, NULL, NULL) == FALSE)
{
throw std::exception("Failed to connect.");
}
我将 IO 完成端口与套接字相关联。
if ((m_hIOCP = CreateIoCompletionPort(reinterpret_cast<HANDLE>(m_socket), m_hIOCP, NULL, 8)) == NULL)
{
throw std::exception("Failed to create IOCP object.");
}
在我尝试通过套接字发送一些数据之前,一切似乎都很顺利。
SocketData* socketData = new SocketData;
socketData->hEvent = 0;
DWORD bytesSent = 0;
if (WSASend(m_socket, socketData->SetBuffer(socketData->GenerateLoginRequestHeader()), 1, &bytesSent, NULL, reinterpret_cast<OVERLAPPED*>(socketData), NULL) == SOCKET_ERROR && WSAGetLastError() != WSA_IO_PENDING)
{
throw std::exception("Failed to send data.");
}
WSASend 不会返回 SOCKET_ERROR 并将最后一个错误设置为 WSA_IO_PENDING,而是立即返回。
我需要 IO 挂起并在我的线程函数中处理它的完成,这也是我的工作线程。
unsigned int __stdcall MyClass::WorkerThread(void* lpThis)
{
}
我以前做过,但我不知道在这种情况下出了什么问题,我非常感谢帮助我解决这个问题的任何努力。