問題描述
通過閱讀其他 Stack Overflow 條目和 boost::asio
文檔,我確認沒有同步 ASIO 讀/寫調用也提供易于使用的超時作為調用的參數.
From reading other Stack Overflow entries and the boost::asio
documentation, I've confirmed that there is no synchronous ASIO read/write calls that also provide an easy-to-use timeout as a parameter to the call.
我正在使用使用超時的 select(2) 調用轉換老式 Linux 套接字應用程序,我需要或多或少地做同樣的事情.
I'm in the middle of converting an old-school Linux socket application with select(2) calls that employs timeouts, and I need to do more-or-less the same.
那么在 boost::asio
中執行此操作的最佳方法是什么?查看 asio 文檔,有許多與計時器有關的各種事情的令人困惑的示例,但我很困惑.
So what is the best way to do this in boost::asio
? Looking at the asio documentation, there are many confusing examples of various things to do with timers, but I'm quite confused.
我很想看到一個簡單易讀的例子:從套接字讀取,但最多等待 X 秒,之后函數要么不返回任何內容,要么返回任何內容能夠在超時到期之前從套接字讀取.
I'd love to see a simple-to-read example of this: Read from a socket, but wait for a maximum of X seconds after which the function either returns with nothing, or returns with whatever it was able to read from the socket before the timeout expired.
推薦答案
這已在 asio 郵件列表中提出,有一個 ticket 也請求該功能.總而言之,如果您需要超時和可取消性,建議使用異步方法.
This has been brought up on the asio mailing lists, there's a ticket requesting the feature as well. To summarize, it is suggested to use asynchronous methods if you desire timeouts and cancellability.
如果您無法轉換為異步方法,您可以嘗試SO_RCVTIMEO
和SO_SNDTIMEO
套接字選項.它們可以用 setsockopt
設置,描述符可以用 boost::asio::ip::tcp::socket::native 方法.man 7 socket
手冊頁說
If you cannot convert to asynchronous methods, you might try the SO_RCVTIMEO
and SO_SNDTIMEO
socket options. They can be set with setsockopt
, the descriptor can be obtained with the boost::asio::ip::tcp::socket::native method. The man 7 socket
man page says
SO_RCVTIMEO 和 SO_SNDTIMEO指定接收或發送超時,直到報告錯誤.參數是一個結構體時間.如果輸入或輸出這個時期的功能塊時間,并且數據已經發送或收到,該函數的返回值將是傳輸的數據量;如果不數據已傳輸并且已達到超時然后 -1 是返回 errno 設置為EAGAIN 或 EWOULDBLOCK 就像套接字被指定為是非阻塞的.如果超時是設置為零(默認)然后操作永遠不會超時.超時僅有效對于執行套接字 I/O 的系統調用(例如,read(2),recvmsg(2), send(2), sendmsg(2));超時對 select(2) 沒有影響,poll(2)、epoll_wait(2) 等
SO_RCVTIMEO and SO_SNDTIMEO Specify the receiving or sending timeouts until reporting an error. The argument is a struct timeval. If an input or output function blocks for this period of time, and data has been sent or received, the return value of that function will be the amount of data transferred; if no data has been transferred and the timeout has been reached then -1 is returned with errno set to EAGAIN or EWOULDBLOCK just as if the socket was specified to be non-blocking. If the timeout is set to zero (the default) then the operation will never timeout. Timeouts only have effect for system calls that perform socket I/O (e.g., read(2), recvmsg(2), send(2), sendmsg(2)); timeouts have no effect for select(2), poll(2), epoll_wait(2), etc.
這篇關于C++ Boost ASIO:如何讀/寫超時?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!