为什么WSASend返回0但仍然调用完成例程?

时间:2014-03-16 07:06:57

标签: c++ windows winsock winsock2 overlapped-io

文档明确指出,如果WSASend立即完成,那么您将获得WSA_IO_PENDING,但这并不会发生。我总是得到0,dwBytesTransferred总是匹配我发送的字节。然而,似乎有时我的完成例程被调用,有时,它不是。我为发送分配缓冲区,所以如果完成例程不被调用,我需要释放缓冲区。

我有三个即兴计数器,m_dwAsyncSend,m_dwSyncSend和m_dwCompletions。 m_dwAsycSend始终为零,并且m_dwSyncSend和m_dwCompletions总是相距很远,因为一个m_dwSyncSend可能是750而m_dwCompletions是2.有很多次线程是可警告的,所以我不认为我挨饿就这样。

这让我发疯了!午夜过后,我整天都在这。我责怪,如果其中任何一个是不连贯的!

这里是代码,我认为您不需要类文件来查看我正在做的事情。

void
CALLBACK
SendCompletion(
    DWORD dwError,
    DWORD cbTransferred,
    LPOVERLAPPED pOvl,
    DWORD dwFlags
    )
{
    LPWSABUF pBuffer = (LPWSABUF)((DWORD_PTR)pOvl + sizeof(OVERLAPPED));
    CNetAsyncSocket *pSock = (CNetAsyncSocket *)pOvl->hEvent;
    pSock->m_dwCompletions++;
    if(dwError != NO_ERROR)
    {
        // If things didn't go as planned, ring the bell and disconnect.
        pSock->Disconnect();
        tracef(TT_REGULAR, 1,
            "SOCKET_ERROR in CNetAsyncSocket::Send(), disconnecting, error code: %ld, on socket: %s:%ld",
            dwError, pSock->GetIP(), pSock->GetPort());
        free(pOvl);
    }
    else
    {
        // If we sent less than we meant to, queue up the rest.
        if(cbTransferred < pBuffer->len)
        {
            DWORD dwRemaining = pBuffer->len - cbTransferred;
            memmove(pBuffer->buf, (PVOID)((DWORD_PTR)pBuffer->buf + dwRemaining), dwRemaining);
            pBuffer->len = dwRemaining;
        }
        else
        {
            free(pOvl);
        }
    }
}
void CNetAsyncSocket::SendAsync(PBYTE pData, DWORD dwLength)
{
    // We want to minimize heap churn, so let's do this in one allocation.
    // Also, having this in one chunk of memory makes it easier to interpret
    // it on the other side.
    DWORD dwAllocSize =
        sizeof(OVERLAPPED) +        // The OVERLAPPED struct.
        sizeof(WSABUF) +            // The buffer info.
        dwLength;                   // The actual buffer we're copying.
    LPOVERLAPPED pOvl = (LPOVERLAPPED)malloc(dwAllocSize);

    if(pOvl == NULL)
    {
        // Out of memory.
    }

    // Initialize the allocation.
    ZeroMemory(pOvl, dwAllocSize);


    // Build the pointers.
    LPWSABUF pBuffer = (LPWSABUF)((DWORD_PTR)pOvl + sizeof(OVERLAPPED));
    pBuffer->len = dwLength;
    assert(pBuffer->len < 1000000);
    pBuffer->buf = (PCHAR)((DWORD_PTR)pBuffer + sizeof(WSABUF));
    // When you have a completion routine, the hEvent member is ignored, so we
    // can use it to pass our this pointer to the completion routine.
    pOvl->hEvent = (PVOID)this;

    // Copy the data to the buffer.
    CopyMemory(pBuffer->buf, pData, dwLength);

    // Send the data.
    DWORD dwSent = 0;
    int iResult = WSASend(
        m_hSocket,          // The socket.
        pBuffer,            // The WSABUF struct.
        1,                  // Number of structs (1).
        &dwSent,            // Bytes sent. Updated if it happens synchronously.
        0,                  // No flags.
        pOvl,               // The overlapped struct.
        SendCompletion);    // Completion routine.

    if(iResult == NO_ERROR)
    {
        // If the send happened synchronously, we can go ahead and delete the
        // memory that we allocated.

        // TODO: look at bytes transferred, and if they're less than the total
        // then issue another send with the remainder.

        if(HasOverlappedIoCompleted(pOvl))
        {
            // If I actually free this here, the completion routine gets garbage.
            //free(pOvl);
            m_dwSyncSend++;
        }
        else
        {
            m_dwAsyncSend++;
        }
    }
    else
    {
        // If we got WSA_IO_PENDING, then that just means the completion routine
        // will take care of it.
        if(iResult != WSA_IO_PENDING)
        {
            Disconnect();
            tracef(TT_REGULAR, 1,
                "SOCKET_ERROR in CNetAsyncSocket::Send(), disconnecting, error code: %ld, on socket: %s:%ld",
                iResult, GetIP(), GetPort());
            // Don't need the payload anymore.
            free(pOvl);
        }
        else
        {
            m_dwAsyncSend++;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

文档说如果操作可以立即完成,你将获得0,如果不能,则获得SOCKET_ERROR(最后一个错误代码为WSA_IO_PENDING)。无论哪种方式,对完成例程的调用都将排队。

因此,您所描述的行为是预期的,并且唯一应该释放缓冲区的情况是,如果发生了WSA_IO_PENDING以外的错误。