Multithreaded IOCP Client Issue

Posted by Carl on Stack Overflow See other posts from Stack Overflow or by Carl
Published on 2010-06-11T03:47:20Z Indexed on 2010/06/11 3:53 UTC
Read the original article Hit count: 381

Filed under:
|

I am writing a multithreaded client that uses an IO Completion Port.

I create and connect the socket that has the WSA_FLAG_OVERLAPPED attribute set.

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.");
}

I associate the IO Completion Port with the socket.

if ((m_hIOCP = CreateIoCompletionPort(reinterpret_cast<HANDLE>(m_socket), m_hIOCP, NULL, 8)) == NULL)
{
    throw std::exception("Failed to create IOCP object.");
}

All appears to go well until I try to send some data over the socket.

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.");
}

Instead of returning SOCKET_ERROR with the last error set to WSA_IO_PENDING, WSASend returns immediately.

I need the IO to pend and for it's completion to be handled in my thread function which is also my worker thread.

unsigned int __stdcall MyClass::WorkerThread(void* lpThis)
{

}

I've done this before but I don't know what is going wrong in this case, I'd greatly appreciate any efforts in helping me fix this problem.

© Stack Overflow or respective owner

Related posts about client

Related posts about iocp