c - 如何将缓冲区放入 CompletionROUTINE 作为 WSARecvFrom 调用的一部分?

标签 c windows winsock2

我正在 UDP 服务器上工作,并尝试使用重叠 IO。我一直在尝试使用 MSDN 示例和文档进行研究,但尚未找到该函数的 lpCompletionRoutine 参数的使用。

我注意到您将 PWSAOVERLAPPED 传递给 WSARecvFrom,并且它包含一个 LPVOID Pointer 成员。我是否可以创建自己的用户数据结构,其中包含对缓冲区的引用,并将其作为指针传递到 PWSAOVERLAPPED 的此 Pointer 成员中?

我认为这有点多余,尽管接收到的字节在两个地方可用:

WSARecvFromlpNumberOfBytesRecvd 参数和 lpCompletionRoutinecbTransferred 参数。

我当前完成例程的示例:

void CALLBACK CompletionROUTINE(
  DWORD dwError, 
  DWORD cbTransferred, 
  LPWSAOVERLAPPED lpOverlapped, 
  DWORD dwFlags
) {
    UNREFERENCED_PARAMETER(dwError);
    UNREFERENCED_PARAMETER(lpOverlapped);
    UNREFERENCED_PARAMETER(dwFlags);

    /* Best way to get the bytes read here? */
    Printf(L"Recieved %d bytes\n", cbTransferred);
}

以及我对 WSARecvFrom 的调用:

iResult = WSARecvFrom(
    listenSocket, 
    &wsaBuffer, 
    1, 
    &dwBytesRecieved, 
    &dwFlags, 
    (PSOCKADDR)&sender, 
    &senderAddrSize, 
    &wsaOverlapped,
    CompletionROUTINE
);

最佳答案

来自WSAOVERLAPPED结构documentation :

hEvent Type: HANDLE If an overlapped I/O operation is issued without an I/O completion routine (the operation's lpCompletionRoutine parameter is set to null), then this parameter should either contain a valid handle to a WSAEVENT object or be null. If the lpCompletionRoutine parameter of the call is non-null then applications are free to use this parameter as necessary.

因此,由于我提供了 lpCompletionRoutine 参数,因此我可以使用 WSAEvent 作为指向用户定义数据的指针。

感谢评论者引导我得出这一发现。

关于c - 如何将缓冲区放入 CompletionROUTINE 作为 WSARecvFrom 调用的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50736594/

相关文章:

c++ - HeapAlloc 间歇性失败

c++ - 将调用线程置于可警告等待状态

windows - MS.Win32.Penimc.UnsafeNativeMethods Visual Studio 2015 和 Sql Server Management Studio 2012

python - 在 python 中与 Windows CMD 交互

c - 使用套接字在 C 中发送发布数据时出错

c++ - 单缓冲区阻塞WSASend可以传递部分数据吗?

c++ - 这是允许的 : memcpy(dest, src, 0)

C 编程寄存器值?

c - 我在 c 中得到了意外的输出 .. 谁能解释为什么?

c - 初始化类型错误时类型不兼容