我不能同意这是“正常的”,就像上面发布的那样。
在您的呼叫中,recvfrom
您将收到一个错误recv_len
。我建议检查该值 - 它将是SOCKET_ERROR
并且通过调用WSAGetLastErrorenter
您会看到错误WSAEWOULDBLOCK
。
我不是(Windows)套接字专家,但根据我的测试,我不能在非阻塞模式下使用ioctlsocket
和的组合来通过 UDP 接收数据(我在你的例子中做了和你一样的事情)。recvfrom
我计划使用select
和recvfrom
最小可能超时(1us)的组合。我现在不知道任何其他可能更好的解决方案。
ioctlsocket
注意:您还应该检查可能的错误的返回值。
我将在今天晚些时候提供我的代码示例。
更新(按承诺添加代码):
/* define list of sockets for function select(..) */
fd_set readfds;
/* define timeout for function select(..) */
TIMEVAL tv;
/* timeout: 1us */
tv.tv_usec = 1;
/* timeout: 0s */
tv.tv_sec = 0;
/* just 1 socket is used */
readfds.fd_count = 1;
readfds.fd_array[0] = receivingSocket;
/* determine the status of one or more sockets with timeout */
int selectReturnValue = select(0, &readfds, 0, 0, &tv);
/* check return value of the call of function select(..) */
switch (selectReturnValue)
{
/* select(..) function timeout */
case 0:
/* time limit expired */
break;
/* select(..) function error */
case SOCKET_ERROR:
/* check the error status for the last windows sockets operation */
selectError(WSAGetLastError());
break;
/* no timeout and no error */
default:
/* receive data from UDP */
resultOfrecvfrom = recvfrom(receivingSocket, receivingBuffer, sizeof(receivingBuffer), 0, (SOCKADDR *)&serverReceptionInfo, &serverReceptionInfoLength);
/* check result of call of recvfrom(..) */
switch (resultOfrecvfrom)
{
/* connection has been gracefully closed */
case 0:
/* socket was closed */
break;
/* socket error occurred during last call of socket operation */
case SOCKET_ERROR:
/* check the error status for the last Windows Sockets operation */
recvfromError(WSAGetLastError());
break;
/* resultOfrecvfrom amount of data received */
default:
/* ... add your code here */
break;
}
break;
}
如果需要更多,我只是复制了我的代码的关键部分,请在评论中告诉我。