IOCP Sample Code

|

IOCP - Sample Code

 

 

DWORD WINAPI WorkerThread(LPVOID lpParam) 
{     
ULONG_PTR      *PerHandleKey; 
OVERLAPPED      *Overlap; 
    OVERLAPPEDPLUS *OverlapPlus, 
  *newolp; 
    DWORD             dwBytesXfered; 

while (1) 
    { 
        ret = GetQueuedCompletionStatus( 
            hIocp, 
            &dwBytesXfered, 
            (PULONG_PTR)&PerHandleKey, 
            &Overlap, 
            INFINITE); 
        if (ret == 0) 
        { 
            // Operation failed 
            continue; 
        } 
        OverlapPlus = CONTAINING_RECORD(Overlap, OVERLAPPEDPLUS, ol); 
        switch (OverlapPlus->OpCode) 
{ 
    case OP_ACCEPT: 
        // Client socket is contained in  
// OverlapPlus.sclient 
// Add client to completion port 
CreateIoCompletionPort( 
(HANDLE)OverlapPlus->sclient, 
hIocp, 
(ULONG_PTR)0, 
0); 
        // Need a new OVERLAPPEDPLUS structure 
        //  for the newly accepted socket. Perhaps 
        //  keep a look aside list of free structures. 
        newolp = AllocateOverlappedPlus(); 
        if (!newolp) 
{ 
    // Error 
} 
newolp->s = OverlapPlus->sclient; 
newolp->OpCode = OP_READ; 
// This function prepares the data 
// to be sent 
PrepareSendBuffer(&newolp->wbuf); 

ret = WSASend( 
    newolp->s, 
    &newolp->wbuf, 
       1, 
    &newolp->dwBytes, 
0, 
&newolp.ol, 
NULL); 
if (ret == SOCKET_ERROR) 
{ 
    if (WSAGetLastError() != WSA_IO_PENDING) 
    { 
        // Error 
} 
} 

// Put structure in look aside list for later use 
FreeOverlappedPlus(OverlapPlus); 

// Signal accept thread to issue another AcceptEx 
SetEvent(hAcceptThread); 
        break; 
    case OP_READ: 
        // Process the data read     
        // … 

        // Repost the read if necessary, reusing the same 
        //  receive buffer as before 
        memset(&OverlapPlus->ol, 0, sizeof(OVERLAPPED)); 
ret = WSARecv( 
            OverlapPlus->s, 
            &OverlapPlus->wbuf, 
            1, 
            &OverlapPlus->dwBytes, 
            &OverlapPlus->dwFlags, 
            &OverlapPlus->ol, 
            NULL); 
    if (ret == SOCKET_ERROR) 
{ 
    if (WSAGetLastError() != WSA_IO_PENDING) 
    { 
        // Error 
    } 
} 
break; 
    case OP_WRITE: 
        // Process the data sent, etc. 
        // … 

        break; 
    //… 
} 
    } 
}

And