gpt4 book ai didi

timeout - recv() Windows 套接字需要无限时间 - 如何超时?

转载 作者:行者123 更新时间:2023-12-04 17:27:13 25 4
gpt4 key购买 nike

我使用文件描述符来查找可读的套接字并继续阅读。出于某些原因,线路上没有数据的套接字会继续读取并且永不返回。有没有办法在超时后退出接收?

我正在使用 winsock 库..

最佳答案

http://tangentsoft.net/wskfaq/newbie.html#timeout

2.15 - 如何更改 Winsock 函数的超时时间?

一些阻塞的 Winsock 函数(例如 connect())嵌入了超时。这背后的理论是,只有堆栈具有设置正确超时所需的所有信息。然而,有些人发现堆栈使用的值对于他们的应用程序来说太长了;它可以是一分钟或更长时间。

您可以使用 SO_SNDTIMEO 和 SO_RCVTIMEO setsockopt() 选项调整 send() 和 recv() 超时。 .

对于其他 Winsock 函数,最好的解决方案是完全避免阻塞套接字。所有非阻塞套接字方法都为您提供了构建自定义超时的方法:

Non-blocking sockets with select() – The fifth parameter to the select() function is a timeout value.

Asynchronous sockets – Use the Windows API SetTimer().

Event objects – WSAWaitForMultipleEvents() has a timeout parameter.

Waitable Timers – Call CreateWaitableTimers() to make a waitable timer, which you can then pass to a function like WSAEventSelect() along with your sockets: if none of the sockets is signalled before the timer goes off, the blocking function will return anyway.

请注意,使用异步和非阻塞套接字,您可以完全避免处理超时。即使 Winsock 很忙,您的程序也会继续工作。因此,您可以让用户取消耗时过长的操作,或者让 Winsock 的自然超时到期而不是在您的代码中接管此功能。

关于timeout - recv() Windows 套接字需要无限时间 - 如何超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6755637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com