recv() Windows 套接字需要无限时间 - 如何超时?
我使用文件描述符来查找可读套接字并继续读取。由于某些原因,线路上没有数据的套接字会继续读取并且永远不会返回。有没有办法让我在超时后退出接收?
我正在使用winsock库..
I use file descriptors to find the readable sockets and go on to read. For some reasons, a socket that has no data on the wire, goes on to read and never returns. Is there a way I can come out of the receive after a timeout?
I am using winsock library..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
http://tangentsoft.net/wskfaq/newbie.html#timeout
2.15 - 如何更改超时Winsock 函数?
一些阻塞Winsock 函数(例如connect())中嵌入了超时。这背后的理论是,只有堆栈拥有设置适当超时所需的所有信息。然而,有些人发现堆栈使用的值对于他们的应用程序来说太长了;可以是一分钟或更长时间。
您可以使用 SO_SNDTIMEO 和 SO_RCVTIMEO setsockopt() 选项调整 send() 和 receive() 超时。 。
对于其他 Winsock 函数,最好的解决方案是完全避免阻塞套接字。所有非阻塞套接字方法都为您提供了构建自定义超时的方法:
请注意,使用异步和非阻塞套接字,您可以完全避免处理超时。即使 Winsock 很忙,您的程序也会继续工作。因此,您可以让用户自行取消耗时过长的操作,或者只是让 Winsock 的自然超时到期,而不是在代码中接管此功能。
http://tangentsoft.net/wskfaq/newbie.html#timeout
2.15 - How can I change the timeout for a Winsock function?
Some of the blocking Winsock functions (e.g. connect()) have a timeout embedded into them. The theory behind this is that only the stack has all the information necessary to set a proper timeout. Yet, some people find that the value the stack uses is too long for their application; it can be a minute or longer.
You can adjust the send() and recv() timeouts with the SO_SNDTIMEO and SO_RCVTIMEO setsockopt() options. .
For other Winsock functions, the best solution is to avoid blocking sockets altogether. All of the non-blocking socket methods provide ways for you to build custom timeouts:
Note that with asynchronous and non-blocking sockets, you may be able to avoid handling timeouts altogether. Your program continues working even while Winsock is busy. So, you can leave it up to the user to cancel an operation that’s taking too long, or just let Winsock’s natural timeout expire rather than taking over this functionality in your code.
你的问题出在你尝试填充缓冲区的 while 循环中
只需放置一个 if 语句来检查每个块的最后一个索引是否为 '\0'
然后打破你的 while 循环
your problem is in the while loop that you try to fill buffer
just put an if statement that check last index of every chunks for '\0'
then break your while loop