

How to set a timeout on blocking sockets in boost asio?
FULL ANSWER This question keep being asked over and over again for many years. Answers I saw so far are quite poor. I’ll add this info right here in one of the first occurrences of this question.
Everybody trying to use ASIO to simplify their networking code would be perfectly happy if the author would just add an optional parameter timeout to all sync and async io functions. Unfortunately, this is unlikely to happen (in my humble opinion, just for ideological reasons, after all, AS in ASIO is for a reason).
So these are the ways to skin this poor cat available so far, none of them especially appetizing. Let’s say we need 200ms timeout.
1) Good (bad) old socket API:
Please note those peculiarities: – const int for timeout – on Windows the required type is actually DWORD, but the current set of compilers luckily has it the same, so const int will work both in Win and Posix world. – (const char*) for value. On Windows const char* is required, Posix requires const void*, in C++ const char* will convert to const void* silently while the opposite is not true.
Advantages: works and probably will always work as the socket API is old and stable. Simple enough. Fast. Disadvantages: technically might require appropriate header files (different on Win and even different UNIX flavors) for setsockopt and the macros, but current implementation of ASIO pollutes global namespace with them anyway. Requires a variable for timeout. Not type-safe. On Windows, requires that the socket is in overlapped mode to work (which current ASIO implementation luckily uses, but it is still an implementation detail). UGLY!
2) Custom ASIO socket option:
Advantages: Simple enough. Fast. Beautiful (with typedef). Disadvantages: Depends on ASIO implementation detail, which might change (but OTOH everything will change eventually, and such detail is less likely to change then public APIs subject to standardization). But in case this happens, you’ll have to either write a class according to https://www.boost.org/doc/libs/1_68_0/doc/html/boost_asio/reference/SettableSocketOption.html (which is of course a major PITA thanks to obvious overengineering of this part of ASIO) or better yet revert to 1.
3) Use C++ async/future facilities.
Advantages: standard. Disadvantages: always starts a new thread (in practice), which is relatively slow (might be good enough for clients, but will lead to DoS vulnerability for servers as threads and sockets are “expensive” resources). Don’t try to use std::launch::deferred instead of std::launch::async to avoid new thread launch as wait_for will always return future_status::deferred without trying to run the code.
4) The method prescribed by ASIO – use async operations only (which is not really the answer to the question).
Advantages: good enough for servers too if huge scalability for short transactions is not required. Disadvantages: quite wordy (so I will not even include examples – see ASIO examples). Requires very careful lifetime management of all your objects used both by async operations and their completion handlers, which in practice requires all classes containing and using such data in async operations be derived from enable_shared_from_this, which requires all such classes allocated on heap, which means (at least for short operations) that scalability will start taper down after about 16 threads as every heap alloc/dealloc will use a memory barrier.
More Related Contents:
- Boost::asio – how to interrupt a blocked tcp server thread?
- Why do I need strand per connection when using boost::asio?
- What is the usefulness of `enable_shared_from_this`?
- How to create a thread pool using boost in C++?
- Should the exception thrown by boost::asio::io_service::run() be caught?
- Best documentation for Boost:asio?
- boost asio ssl async_shutdown always finishes with an error?
- Cancelling boost asio deadline timer safely
- Boost async_* functions and shared_ptr’s
- Boost ASIO streambuf
- Copy a streambuf’s contents to a string
- C++ Boost ASIO simple periodic timer?
- When must you pass io_context to boost::asio::spawn? (C++)
- BOOST ASIO – How to write console server
- Exception running boost asio ssl example
- Boost.Asio as header-only
- asio How to change the executor inside an awaitable?
- Strange exception throw – assign: Operation not permitted
- Why does Boost.Asio not support an event-based interface?
- Weighted random numbers
- Magic number in boost::hash_combine
- C++ – Why is boost::hash_combine the best way to combine hash-values?
- Boost C++ Serialization overhead
- Why do we need to use boost::asio::io_service::work?
- Use channel hiearchy of Boost.Log for severity and sink filtering
- Does boost have a datatype for set operations that is simpler than the STL?
- C++ OpenCV image sending through socket
- How to build boost Version 1.58.0 using Visual Studio 2015 (Enterprise)
- boost::asio + std::future – Access violation after closing socket
- boost::asio with boost::unique_future
Leave a Comment Cancel reply
Save my name, email, and website in this browser for the next time I comment.
Search code, repositories, users, issues, pull requests...
Provide feedback.
We read every piece of feedback, and take your input very seriously.
Saved searches
Use saved searches to filter your results more quickly.
To see all available qualifiers, see our documentation .
- Notifications
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
boost/beast: idle timeout of websocket can be delivered to caller by async_write? #1712
asdfping commented Sep 25, 2019 • edited
vinniefalco commented Sep 25, 2019
Sorry, something went wrong.
asdfping commented Sep 26, 2019
No branches or pull requests
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
setsockopt function (winsock.h)
The setsockopt function sets a socket option.
A descriptor that identifies a socket.
The level at which the option is defined (for example, SOL_SOCKET).
[in] optname
The socket option for which the value is to be set (for example, SO_BROADCAST). The optname parameter must be a socket option defined within the specified level , or behavior is undefined.
[in] optval
A pointer to the buffer in which the value for the requested option is specified.
[in] optlen
The size, in bytes, of the buffer pointed to by the optval parameter.

Return value
If no error occurs, setsockopt returns zero. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling WSAGetLastError .
The setsockopt function sets the current value for a socket option associated with a socket of any type, in any state. Although options can exist at multiple protocol levels, they are always present at the uppermost socket level. Options affect socket operations, such as whether expedited data (OOB data for example) is received in the normal data stream, and whether broadcast messages can be sent on the socket.
The following tables list some of the common options supported by the setsockopt function. The Type column identifies the type of data addressed by optval parameter. The Description column provides some basic information about the socket option. For more complete lists of socket options and more detailed information (default values, for example), see the detailed topics under Socket Options .
level = SOL_SOCKET
level = IPPROTO_TCP
See TCP_NODELAY in IPPROTO_TCP socket options . Also see that topic for more complete and detailed information about socket options for level = IPPROTO_TCP .
level = NSPROTO_IPX
For more complete and detailed information about socket options for level = NSPROTO_IPX , see NSPROTO_IPX Socket Options .
BSD options not supported for setsockopt are shown in the following table.
Example Code
Notes for irda sockets.
When developing applications using Windows sockets for IrDA, note the following:
- The Af_irda.h header file must be explicitly included.
The IRLMP_IAS_SET socket option enables the application to set a single attribute of a single class in the local IAS. The application specifies the class to set, the attribute, and attribute type. The application is expected to allocate a buffer of the necessary size for the passed parameters.
IrDA provides an IAS database that stores IrDA-based information. Limited access to the IAS database is available through the Windows Sockets 2 interface, but such access is not normally used by applications, and exists primarily to support connections to non-Windows devices that are not compliant with the Windows Sockets 2 IrDA conventions.
The following structure, IAS_SET , is used with the IRLMP_IAS_SET setsockopt option to manage the local IAS database:
The following structure, IAS_QUERY , is used with the IRLMP_IAS_QUERY setsockopt option to query a peer's IAS database:
Many SO_ level socket options are not meaningful to IrDA. Only SO_LINGER is specifically supported.
Windows Phone 8: This function is supported for Windows Phone Store apps on Windows Phone 8 and later.
Windows 8.1 and Windows Server 2012 R2 : This function is supported for Windows Store apps on Windows 8.1, Windows Server 2012 R2, and later.
Requirements
IPPROTO_IP Socket Options
IPPROTO_IPV6 Socket Options
IPPROTO_RM Socket Options
IPPROTO_TCP Socket Options
IPPROTO_UDP Socket Options
NSPROTO_IPX Socket Options
SOL_APPLETALK Socket Options
SOL_IRLMP Socket Options
SOL_SOCKET Socket Options
Socket Options
WSAAsyncSelect
WSAEventSelect
Winsock Functions
ioctlsocket
Was this page helpful?
Submit and view feedback for
Additional resources
Boost C++ Libraries
...one of the most highly regarded and expertly designed C++ library projects in the world. — Herb Sutter and Andrei Alexandrescu , C++ Coding Standards

While basic_stream and tcp_stream support timeouts on general logical operations, the websocket stream has a more sophisticated timeout mechanism built-in which may be enabled and configured. The timeout features of the TCP or basic stream should not be used when working with a websocket stream. The interface to these timeout features is shown in this table.
Table 1.36. WebSocket Timeout Interface
There are three timeout settings which may be set independently on the stream:
Table 1.37. WebSocket Timeout Interface (2)
By default, timeouts on websocket streams are disabled. The easiest way to turn them on is to set the suggested timeout settings on the stream.
For manual control over the settings, a timeout options object may be constructed. Here we enable only the handshake timeout.
Timeout notifications are delivered to the caller by invoking the completion handler for an outstanding asynchronous read operation with the error code error :: timeout . The implementation will close the socket or stream before delivering this error. It is not necessary to manually shut down the connection, as it will already be shut down. A read operation must be outstanding for the error to be delivered.
The timeouts on the websocket stream are incompatible with the timeouts used in the tcp_stream . When constructing a websocket stream from a tcp stream that has timeouts enabled, the timeout should be disabled first before constructing the websocket stream, as shown.
Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt )
Boost C++ Libraries
...one of the most highly regarded and expertly designed C++ library projects in the world. — Herb Sutter and Andrei Alexandrescu , C++ Coding Standards

socket_base::linger
Socket option to specify whether the socket lingers on close if unsent data is present.
Implements the SOL_SOCKET/SO_LINGER socket option.
Setting the option:
Getting the current option value:
Requirements
Header: boost/asio/socket_base.hpp
Convenience header: boost/asio.hpp
Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt )
Make Me Engineer
How to set a timeout on blocking sockets in boost asio?
FULL ANSWER This question keep being asked over and over again for many years. Answers I saw so far are quite poor. I’ll add this info right here in one of the first occurrences of this question.
Everybody trying to use ASIO to simplify their networking code would be perfectly happy if the author would just add an optional parameter timeout to all sync and async io functions. Unfortunately, this is unlikely to happen (in my humble opinion, just for ideological reasons, after all, AS in ASIO is for a reason).
So these are the ways to skin this poor cat available so far, none of them especially appetizing. Let’s say we need 200ms timeout.
1) Good (bad) old socket API:
Please note those peculiarities: – const int for timeout – on Windows the required type is actually DWORD, but the current set of compilers luckily has it the same, so const int will work both in Win and Posix world. – (const char*) for value. On Windows const char* is required, Posix requires const void*, in C++ const char* will convert to const void* silently while the opposite is not true.
Advantages: works and probably will always work as the socket API is old and stable. Simple enough. Fast. Disadvantages: technically might require appropriate header files (different on Win and even different UNIX flavors) for setsockopt and the macros, but current implementation of ASIO pollutes global namespace with them anyway. Requires a variable for timeout. Not type-safe. On Windows, requires that the socket is in overlapped mode to work (which current ASIO implementation luckily uses, but it is still an implementation detail). UGLY!
2) Custom ASIO socket option:
Advantages: Simple enough. Fast. Beautiful (with typedef). Disadvantages: Depends on ASIO implementation detail, which might change (but OTOH everything will change eventually, and such detail is less likely to change then public APIs subject to standardization). But in case this happens, you’ll have to either write a class according to https://www.boost.org/doc/libs/1_68_0/doc/html/boost_asio/reference/SettableSocketOption.html (which is of course a major PITA thanks to obvious overengineering of this part of ASIO) or better yet revert to 1.
3) Use C++ async/future facilities.
Advantages: standard. Disadvantages: always starts a new thread (in practice), which is relatively slow (might be good enough for clients, but will lead to DoS vulnerability for servers as threads and sockets are “expensive” resources). Don’t try to use std::launch::deferred instead of std::launch::async to avoid new thread launch as wait_for will always return future_status::deferred without trying to run the code.
4) The method prescribed by ASIO – use async operations only (which is not really the answer to the question).
Advantages: good enough for servers too if huge scalability for short transactions is not required. Disadvantages: quite wordy (so I will not even include examples – see ASIO examples). Requires very careful lifetime management of all your objects used both by async operations and their completion handlers, which in practice requires all classes containing and using such data in async operations be derived from enable_shared_from_this, which requires all such classes allocated on heap, which means (at least for short operations) that scalability will start taper down after about 16 threads as every heap alloc/dealloc will use a memory barrier.
Related Contents:
- Why do I need strand per connection when using boost::asio?
- What is the usefulness of `enable_shared_from_this`?
- How to create a thread pool using boost in C++?
- Should the exception thrown by boost::asio::io_service::run() be caught?
- Best documentation for Boost:asio?
- Cancelling boost asio deadline timer safely
- boost asio ssl async_shutdown always finishes with an error?
- Boost async_* functions and shared_ptr’s
- Boost ASIO streambuf
- Copy a streambuf’s contents to a string
- Get path of executable
- How do I sort a std::vector by the values of a different std::vector?
- Is this behavior of vector::resize(size_type n) under C++11 and Boost.Container correct?
- boost asio async_write : how to not interleaving async_write calls?
- smart pointers (boost) explained
- Is std::vector or boost::vector thread safe?
- Confused when boost::asio::io_service run method blocks/unblocks
- How can I get the IP Address of a local computer?
- Why override operator()?
- boost_1_60_0 .zip installation in windows
- Why can’t clang with libc++ in c++0x mode link this boost::program_options example?
- make shared_ptr not use delete
- Send and Receive a file in socket programming in Linux with C/C++ (GCC/G++)
- Should we pass a shared_ptr by reference or by value?
- Can I redefine a C++ macro then define it back?
- boost::spirit::qi duplicate parsing on the output
- How do you install Boost on MacOS?
- C++ Boost: undefined reference to boost::system::generic_category()
- Parse quoted strings with boost::spirit
- Very poor boost::lexical_cast performance
- will casting around sockaddr_storage and sockaddr_in break strict aliasing
- Understanding Boost.spirit’s string parser
- Downcasting shared_ptr to shared_ptr?
- A good example for boost::algorithm::join
- Boost.ASIO-based HTTP client library (like libcurl) [closed]
- Using vector as a buffer without initializing it on resize()
- Thread safe implementation of circular buffer
- C++ Socket Server – Unable to saturate CPU
- Bad alloc is thrown
- Where is shared_ptr?
- Get current time in milliseconds using C++ and Boost
- C++ Boost: what’s the cause of this warning?
- Which C++ signals/slots library should I choose? [closed]
- xcode with boost : linker(Id) Warning about visibility settings
- How do you throttle the bandwidth of a socket connection in C?
- C++ & Boost: encode/decode UTF-8
- Possible causes for Boost not being found by CMake in certain situations?
- c++ work queues with blocking
- Conversion from boost::shared_ptr to std::shared_ptr?
- boost::property_tree XML pretty printing
Leave a Comment Cancel reply
Save my name, email, and website in this browser for the next time I comment.

IMAGES
VIDEO
COMMENTS
socket.set_option(boost::asio::detail::socket_option::integer<SOL_SOCKET, SO_RCVTIMEO>{ 200 }); FULL ANSWER This question keep being asked over and over again for many years. Answers I saw so far are quite poor. I'll add this info right here in one of the first occurrences of this question.
I am required to set the options boost::asio::ip::tcp::no_delay and boost::asio::socket_base::linger for a boost::asio::ip::tcp::socket that connects to a remote TCP server. I used the method set_option in order to achieve this without any problems.. The question(s): once the io_service is run()ing and the socket opened, if I'm asked to change its options (i.e.: due to a change in the program ...
When set to true, Boost.Asio will set the underlying file descriptor to be non-blocking and synchronous Boost.Asio socket operations can fail with boost::asio::error::would_block (or the equivalent system error). When set to false, Boost.Asio will block, even if the underlying file descriptor is non-blocking, by polling the file descriptor and ...
basic_socket::set_option (1 of 2 overloads) Set an option on the socket. template< typename SettableSocketOption > void set_option( const SettableSocketOption & option); This function is used to set an option on the socket.
ip::tcp::socket. The TCP socket type. Socket option to permit sending of broadcast messages. IO control command to get the amount of data that can be read without blocking. Socket option to enable socket-level debugging. Socket option to prevent routing, use local interfaces only.
Sorry that you've had problems with boost::asio. While it's definitely a learning curve and there are a lot of things that have to be done "just right", I've found that for cross-platform development of applications under heavy network load (to the point that synchronous calls like select(), were causing major bottlenecks), boost::asio has performed extremely well and given definite benefits.
basic_socket::set_option (2 of 2 overloads) Set an option on the socket. template< typename SettableSocketOption > boost::system::error_code set_option( const SettableSocketOption & option, boost::system::error_code & ec); This function is used to set an option on the socket.
The socket will have its own executor, // which in the call below is a new strand for the I/O context. net:: ip:: ... When a timeout is set, it cancels any previous read or write timeout for which no outstanding operation is in progress. ... This function // launches a "fiber" which is a coroutine that has its own separately // allocated stack ...
Both the client and the server are using boost sockets. I see that, when the client sends a shutdown connection command: mysocket.shutdown ( boost::asio::ip::tcp::socket::shutdown_both, error_code);, and my client C++ application closes down a 2 seconds later, I get TIME_WAIT on the output of ss -ap | grep application_port.
socket_base::linger. Socket option to specify whether the socket lingers on close if unsent data is present. typedef implementation_defined linger; Implements the SOL_SOCKET/SO_LINGER socket option.
The easiest way to turn them on is to set the suggested timeout settings on the stream. // Apply suggested timeout options for the server role to the stream ws. set_option (stream_base:: timeout:: suggested (role_type:: server)); For manual control over the settings, a timeout options object may be constructed.
socket.set_option(boost::asio::detail::socket_option::integer<SOL_SOCKET, SO_RCVTIMEO>{ 200 }); FULL ANSWER This question keep being asked over and over again for many years. Answers I saw so far are quite poor. I'll add this info right here in one of the first occurrences of this question.
Version of boost we are using: 1.71.0 Hi, we want to impement sync methods for ws with timeout, we already did this for the tcp socket using the async methods, just like in this example from boost asio and we wanted to try the same thing...
I've been trying to find a way to set a timeout without converting my entire code to async, and I've come across this code: get_lowest_layer(*_ws).set_option(boost::asio::detail::socket_option::integer<SOL_SOCKET, SO_RCVTIMEO>{ 200 }); and I get the following exception. set_option: Invalid argument. What am I doing wrong?
TL;DR. socket.set_option(boost::asio::detail::socket_option::integer<SOL_SOCKET, SO_RCVTIMEO>{ 200 }); FULL ANSWER
At the same time, to verify idle timeout, the echo server will sleep after recv some messages so the test client can't recv any message for some seconds, that can cause idle_timeout. according to document, idle timeout should be recv by completion handler for async_read. But in my test, completion handler forasync_write can also recv idle ...
To cause an exiting connection to timeout you can use iptables. Just enable a DROP rule on the port you want to disable. So to simulate a timeout for your Samaba server, while an active connection is up, execute the following on the server: sudo iptables -A INPUT -p tcp --dport 445 -j DROP.
Remarks. The setsockopt function sets the current value for a socket option associated with a socket of any type, in any state. Although options can exist at multiple protocol levels, they are always present at the uppermost socket level. Options affect socket operations, such as whether expedited data (OOB data for example) is received in the ...
The easiest way to turn them on is to set the suggested timeout settings on the stream. // Apply suggested timeout options for the server role to the stream ws. set_option (stream_base:: timeout:: suggested (role_type:: server)); For manual control over the settings, a timeout options object may be constructed.
Socket option to specify whether the socket lingers on close if unsent data is present. ... linger option (true, 30); socket. set_option (option); Getting the current option value: ... bool is_set = option. enabled (); unsigned short timeout = option. timeout (); Requirements. Header: boost/asio/socket_base.hpp. Convenience header: boost/asio.hpp.
socket.set_option(boost::asio::detail::socket_option::integer<SOL_SOCKET, SO_RCVTIMEO>{ 200 }); FULL ANSWER This question keep being asked over and over again for many years. Answers I saw so far are quite poor. I'll add this info right here in one of the first occurrences of this question.