send数据时遇到WSAEWOULDBLOCK

进行TCP网络编程, 用send()函数发送数据时,有时会遇到WSAEWOULDBLOCK错误, 这是个什么东东呢?

代码示例

    iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
    if (iResult == SOCKET_ERROR)
    {
       int nLastError = WSAGetLastError();
       if (WSAEWOULDBLOCK == nLastError )
       {
            ...
       }
        ...
    }

WSAEWOULDBLOCK

WSAEWOULDBLOCK
10035
Resource temporarily unavailable.
This error is returned from operations on nonblocking sockets that cannot be completed immediately, for example recv when no data is queued to be read from the socket.
It is a nonfatal error, and the operation should be retried later.
It is normal for WSAEWOULDBLOCK to be reported as the result from calling connect on a nonblocking SOCK_STREAM socket, since some time must elapse for the connection to be established.

WSAEWOULDBLOCK不是致命的错误,相关的操作应该在后续进行重试。

原因分析

WSAEWOULDBLOCK is not really an error but simply tells you that your send buffers are full.
This can happen if you saturate the network or if the other side simply doesn't acknowledge the received data. Take a look at the select() function, which allows you to wait until buffer space is available or a timeout occurs. There is also a way to bind a win32 event to a stream, which then allows its use with WaitForMultipleObjects in case you want to abort waiting early.

应该发送的window kernel buffer满了,需要有空闲时才能发送。

解决方法:

  • Sleep一段时间然后再进行发送
while(nRet == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
{
    Sleep(50);
    nRet = send(...);
}

这种思路最好加上次数的判断,比如超过20次认为发送失败。

  • 增大socketkernel buffer
SOCKET ConnectSocket = ...
...
int nRcvBufferLen = 1024*1024;
int nSndBufferLen = 4*1024*1024;
int nLen          = sizeof(int);
setsockopt(ConnectSocket, SOL_SOCKET, SO_RCVBUF, (char*)&nRcvBufferLen, nLen);
setsockopt(ConnectSocket, SOL_SOCKET, SO_SNDBUF, (char*)&nSndBufferLen, nLen);

进行音视频发送时,如果SO_SNDBUF设置过小,在网络环境不好的时候,会出现花屏的现象(数据来不及发送),网络环境好的时候则不会出现该现象。

References:

https://msdn.microsoft.com/en-us/library/ms740149(VS.85).aspx
https://msdn.microsoft.com/en-us/library/ms740668(v=vs.85).aspx#WSAEWOULDBLOCK
http://www.cnblogs.com/chengxin1982/archive/2009/12/24/1631067.html
http://stackoverflow.com/questions/14546362/how-to-resolve-wsaewouldblock-error
https://bobobobo.wordpress.com/2008/11/09/resolving-winsock-error-10035-wsaewouldblock/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的阅读 13,709评论 5 6
  • 能耐心看我胡扯的朋友一定已经明白MBA是啥意思了,所以我就不赘述了。每个人学习MBA的原因可能都不同,有本科学会计...
    周老棍子阅读 319评论 0 0
  • 健康,是我们人类永恒的话题。像是在Linckia海星客这样可以提供开放工位以及独立办公间给人工作的联合办公空间内的...
    skyjun阅读 1,519评论 1 1
  • 弓运梵音袅袅,弦推莲水涓涓。低吟巅谷起微烟,闻者家家行慢。 对眼凄情切切,垂眉絮语绵绵。功夫巧手换珠...
    周延龙阅读 334评论 2 4
  • 每一种人存在的方式,都是对交错人生的一个延伸。 明晃晃的太阳,穿透齐臀,露肩,抹胸女子厚厚遮阳伞,汗水交织汇聚每一...
    土心强阅读 269评论 0 1

友情链接更多精彩内容