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

This is the documentation for an old version of Boost. Click here to view this page for the latest version.
PrevUpHomeNext

Reference

Requirements on asynchronous operations
Accept handler requirements
Buffer-oriented asynchronous random-access read device requirements
Buffer-oriented asynchronous random-access write device requirements
Buffer-oriented asynchronous read stream requirements
Buffer-oriented asynchronous write stream requirements
Buffered handshake handler requirements
Completion handler requirements
Composed connect handler requirements
Connect handler requirements
Constant buffer sequence requirements
Convertible to const buffer requirements
Convertible to mutable buffer requirements
Datagram socket service requirements
Descriptor service requirements
Endpoint requirements
Gettable serial port option requirements
Gettable socket option requirements
Handlers
Handle service requirements
SSL handshake handler requirements
Internet protocol requirements
I/O control command requirements
I/O object service requirements
Mutable buffer sequence requirements
Object handle service requirements
Protocol requirements
Random access handle service requirements
Raw socket service requirements
Read handler requirements
Resolve handler requirements
Resolver service requirements
Sequenced packet socket service requirements
Serial port service requirements
Service requirements
Settable serial port option requirements
Settable socket option requirements
SSL shutdown handler requirements
Signal handler requirements
Signal set service requirements
Socket acceptor service requirements
Socket service requirements
Stream descriptor service requirements
Stream handle service requirements
Stream socket service requirements
Buffer-oriented synchronous random-access read device requirements
Buffer-oriented synchronous random-access write device requirements
Buffer-oriented synchronous read stream requirements
Buffer-oriented synchronous write stream requirements
Time traits requirements
Timer service requirements
Waitable timer service requirements
Wait handler requirements
Wait traits requirements
Write handler requirements
add_service
asio_handler_allocate
asio_handler_deallocate
asio_handler_invoke
asio_handler_is_continuation
async_connect
async_read
async_read_at
async_read_until
async_result
async_write
async_write_at
basic_datagram_socket
basic_deadline_timer
basic_io_object
basic_raw_socket
basic_seq_packet_socket
basic_serial_port
basic_signal_set
basic_socket
basic_socket_acceptor
basic_socket_iostream
basic_socket_streambuf
basic_stream_socket
basic_streambuf
basic_waitable_timer
basic_yield_context
buffer
buffer_cast
buffer_copy
buffer_size
buffered_read_stream
buffered_stream
buffered_write_stream
buffers_begin
buffers_end
buffers_iterator
connect
const_buffer
const_buffers_1
coroutine
datagram_socket_service
deadline_timer
deadline_timer_service
error::addrinfo_category
error::addrinfo_errors
error::basic_errors
error::get_addrinfo_category
error::get_misc_category
error::get_netdb_category
error::get_ssl_category
error::get_system_category
error::make_error_code
error::misc_category
error::misc_errors
error::netdb_category
error::netdb_errors
error::ssl_category
error::ssl_errors
error::system_category
generic::basic_endpoint
generic::datagram_protocol
generic::raw_protocol
generic::seq_packet_protocol
generic::stream_protocol
handler_type
has_service
high_resolution_timer
invalid_service_owner
io_service
io_service::id
io_service::service
io_service::strand
io_service::work
ip::address
ip::address_v4
ip::address_v6
ip::basic_endpoint
ip::basic_resolver
ip::basic_resolver_entry
ip::basic_resolver_iterator
ip::basic_resolver_query
ip::host_name
ip::icmp
ip::multicast::enable_loopback
ip::multicast::hops
ip::multicast::join_group
ip::multicast::leave_group
ip::multicast::outbound_interface
ip::resolver_query_base
ip::resolver_service
ip::tcp
ip::udp
ip::unicast::hops
ip::v6_only
is_match_condition
is_read_buffered
is_write_buffered
local::basic_endpoint
local::connect_pair
local::datagram_protocol
local::stream_protocol
mutable_buffer
mutable_buffers_1
null_buffers
placeholders::bytes_transferred
placeholders::error
placeholders::iterator
placeholders::signal_number
posix::basic_descriptor
posix::basic_stream_descriptor
posix::descriptor_base
posix::stream_descriptor
posix::stream_descriptor_service
raw_socket_service
read
read_at
read_until
seq_packet_socket_service
serial_port
serial_port_base
serial_port_base::baud_rate
serial_port_base::character_size
serial_port_base::flow_control
serial_port_base::parity
serial_port_base::stop_bits
serial_port_service
service_already_exists
signal_set
signal_set_service
socket_acceptor_service
socket_base
spawn
ssl::context
ssl::context_base
ssl::error::get_stream_category
ssl::error::make_error_code
ssl::error::stream_category
ssl::error::stream_errors
ssl::rfc2818_verification
ssl::stream
ssl::stream::impl_struct
ssl::stream_base
ssl::verify_client_once
ssl::verify_context
ssl::verify_fail_if_no_peer_cert
ssl::verify_mode
ssl::verify_none
ssl::verify_peer
steady_timer
strand
stream_socket_service
streambuf
system_timer
time_traits< boost::posix_time::ptime >
transfer_all
transfer_at_least
transfer_exactly
use_future
use_future_t
use_service
wait_traits
waitable_timer_service
windows::basic_handle
windows::basic_object_handle
windows::basic_random_access_handle
windows::basic_stream_handle
windows::object_handle
windows::object_handle_service
windows::overlapped_ptr
windows::random_access_handle
windows::random_access_handle_service
windows::stream_handle
windows::stream_handle_service
write
write_at
yield_context
boost::system::is_error_code_enum< boost::asio::error::addrinfo_errors >
boost::system::is_error_code_enum< boost::asio::error::basic_errors >
boost::system::is_error_code_enum< boost::asio::error::misc_errors >
boost::system::is_error_code_enum< boost::asio::error::netdb_errors >
boost::system::is_error_code_enum< boost::asio::error::ssl_errors >
boost::system::is_error_code_enum< boost::asio::ssl::error::stream_errors >

Core

Classes

const_buffer
const_buffers_1
coroutine
invalid_service_owner
io_service
io_service::id
io_service::service
io_service::strand
io_service::work
mutable_buffer
mutable_buffers_1
null_buffers
service_already_exists
streambuf
use_future_t
yield_context

Class Templates

basic_io_object
basic_streambuf
basic_yield_context
buffered_read_stream
buffered_stream
buffered_write_stream
buffers_iterator

Free Functions

add_service
asio_handler_allocate
asio_handler_deallocate
asio_handler_invoke
asio_handler_is_continuation
async_read
async_read_at
async_read_until
async_write
async_write_at
buffer
buffer_cast
buffer_copy
buffer_size
buffers_begin
buffers_end
has_service
read
read_at
read_until
spawn
transfer_all
transfer_at_least
transfer_exactly
use_service
write
write_at

Special Values

use_future

Boost.Bind Placeholders

placeholders::bytes_transferred
placeholders::error
placeholders::iterator
placeholders::signal_number

Error Codes

error::basic_errors
error::netdb_errors
error::addrinfo_errors
error::misc_errors

Type Traits

async_result
handler_type
is_match_condition
is_read_buffered
is_write_buffered

Type Requirements

Asynchronous operations
AsyncRandomAccessReadDevice
AsyncRandomAccessWriteDevice
AsyncReadStream
AsyncWriteStream
CompletionHandler
ConstBufferSequence
ConvertibleToConstBuffer
ConvertibleToMutableBuffer
Handler
IoObjectService
MutableBufferSequence
ReadHandler
Service
SyncRandomAccessReadDevice
SyncRandomAccessWriteDevice
SyncReadStream
SyncWriteStream
WriteHandler

Networking

Classes

generic::datagram_protocol
generic::datagram_protocol::endpoint
generic::datagram_protocol::socket
generic::raw_protocol
generic::raw_protocol::endpoint
generic::raw_protocol::socket
generic::seq_packet_protocol
generic::seq_packet_protocol::endpoint
generic::seq_packet_protocol::socket
generic::stream_protocol
generic::stream_protocol::endpoint
generic::stream_protocol::iostream
generic::stream_protocol::socket
ip::address
ip::address_v4
ip::address_v6
ip::icmp
ip::icmp::endpoint
ip::icmp::resolver
ip::icmp::socket
ip::resolver_query_base
ip::tcp
ip::tcp::acceptor
ip::tcp::endpoint
ip::tcp::iostream
ip::tcp::resolver
ip::tcp::socket
ip::udp
ip::udp::endpoint
ip::udp::resolver
ip::udp::socket
socket_base

Free Functions

async_connect
connect
ip::host_name

Class Templates

basic_datagram_socket
basic_raw_socket
basic_seq_packet_socket
basic_socket
basic_socket_acceptor
basic_socket_iostream
basic_socket_streambuf
basic_stream_socket
generic::basic_endpoint
ip::basic_endpoint
ip::basic_resolver
ip::basic_resolver_entry
ip::basic_resolver_iterator
ip::basic_resolver_query

Services

datagram_socket_service
ip::resolver_service
raw_socket_service
seq_packet_socket_service
socket_acceptor_service
stream_socket_service

Socket Options

ip::multicast::enable_loopback
ip::multicast::hops
ip::multicast::join_group
ip::multicast::leave_group
ip::multicast::outbound_interface
ip::tcp::no_delay
ip::unicast::hops
ip::v6_only
socket_base::broadcast
socket_base::debug
socket_base::do_not_route
socket_base::enable_connection_aborted
socket_base::keep_alive
socket_base::linger
socket_base::receive_buffer_size
socket_base::receive_low_watermark
socket_base::reuse_address
socket_base::send_buffer_size
socket_base::send_low_watermark

I/O Control Commands

socket_base::bytes_readable
socket_base::non_blocking_io

Type Requirements

AcceptHandler
ComposedConnectHandler
ConnectHandler
DatagramSocketService
Endpoint
GettableSocketOption
InternetProtocol
IoControlCommand
Protocol
RawSocketService
ResolveHandler
ResolverService
SeqPacketSocketService
SettableSocketOption
SocketAcceptorService
SocketService
StreamSocketService

Timers

SSL

Serial Ports

Signal Handling

Classes

deadline_timer
high_resolution_timer
steady_timer
system_timer

Class Templates

basic_deadline_timer
basic_waitable_timer
time_traits
wait_traits

Services

deadline_timer_service
waitable_timer_service

Type Requirements

TimerService
TimeTraits
WaitableTimerService
WaitHandler
WaitTraits

Classes

ssl::context
ssl::context_base
ssl::rfc2818_verification
ssl::stream_base
ssl::verify_context

Class Templates

ssl::stream

Type Requirements

BufferedHandshakeHandler
HandshakeHandler
ShutdownHandler

Classes

serial_port
serial_port_base

Class Templates

basic_serial_port

Services

serial_port_service

Serial Port Options

serial_port_base::baud_rate
serial_port_base::flow_control
serial_port_base::parity
serial_port_base::stop_bits
serial_port_base::character_size

Type Requirements

GettableSerialPortOption
SerialPortService
SettableSerialPortOption

Classes

signal_set

Class Templates

basic_signal_set

Services

signal_set_service

Type Requirements

SignalSetService
SignalHandler

POSIX-specific

Windows-specific

Classes

local::stream_protocol
local::stream_protocol::acceptor
local::stream_protocol::endpoint
local::stream_protocol::iostream
local::stream_protocol::socket
local::datagram_protocol
local::datagram_protocol::endpoint
local::datagram_protocol::socket
posix::descriptor_base
posix::stream_descriptor

Free Functions

local::connect_pair

Class Templates

local::basic_endpoint
posix::basic_descriptor
posix::basic_stream_descriptor

Services

posix::stream_descriptor_service

Type Requirements

DescriptorService
StreamDescriptorService

Classes

windows::object_handle
windows::overlapped_ptr
windows::random_access_handle
windows::stream_handle

Class Templates

windows::basic_handle
windows::basic_object_handle
windows::basic_random_access_handle
windows::basic_stream_handle

Services

windows::object_handle_service
windows::random_access_handle_service
windows::stream_handle_service

Type Requirements

HandleService
ObjectHandleService
RandomAccessHandleService
StreamHandleService

In Boost.Asio, an asynchronous operation is initiated by a function that is named with the prefix async_. These functions will be referred to as initiating functions.

All initiating functions in Boost.Asio take a function object meeting handler requirements as the final parameter. These handlers accept as their first parameter an lvalue of type const error_code.

Implementations of asynchronous operations in Boost.Asio may call the application programming interface (API) provided by the operating system. If such an operating system API call results in an error, the handler will be invoked with a const error_code lvalue that evaluates to true. Otherwise the handler will be invoked with a const error_code lvalue that evaluates to false.

Unless otherwise noted, when the behaviour of an asynchronous operation is defined "as if" implemented by a POSIX function, the handler will be invoked with a value of type error_code that corresponds to the failure condition described by POSIX for that function, if any. Otherwise the handler will be invoked with an implementation-defined error_code value that reflects the operating system error.

Asynchronous operations will not fail with an error condition that indicates interruption by a signal (POSIX EINTR). Asynchronous operations will not fail with any error condition associated with non-blocking operations (POSIX EWOULDBLOCK, EAGAIN or EINPROGRESS; Windows WSAEWOULDBLOCK or WSAEINPROGRESS).

All asynchronous operations have an associated io_service object. Where the initiating function is a member function, the associated io_service is that returned by the get_io_service() member function on the same object. Where the initiating function is not a member function, the associated io_service is that returned by the get_io_service() member function of the first argument to the initiating function.

Arguments to initiating functions will be treated as follows:

— If the parameter is declared as a const reference or by-value, the program is not required to guarantee the validity of the argument after the initiating function completes. The implementation may make copies of the argument, and all copies will be destroyed no later than immediately after invocation of the handler.

— If the parameter is declared as a non-const reference, const pointer or non-const pointer, the program must guarantee the validity of the argument until the handler is invoked.

The library implementation is only permitted to make calls to an initiating function's arguments' copy constructors or destructors from a thread that satisfies one of the following conditions:

— The thread is executing any member function of the associated io_service object.

— The thread is executing the destructor of the associated io_service object.

— The thread is executing one of the io_service service access functions use_service, add_service or has_service, where the first argument is the associated io_service object.

— The thread is executing any member function, constructor or destructor of an object of a class defined in this clause, where the object's get_io_service() member function returns the associated io_service object.

— The thread is executing any function defined in this clause, where any argument to the function has an get_io_service() member function that returns the associated io_service object.

The io_service object associated with an asynchronous operation will have unfinished work, as if by maintaining the existence of one or more objects of class io_service::work constructed using the io_service, until immediately after the handler for the asynchronous operation has been invoked.

When an asynchronous operation is complete, the handler for the operation will be invoked as if by:

  1. Constructing a bound completion handler bch for the handler, as described below.
  2. Calling ios.post(bch) to schedule the handler for deferred invocation, where ios is the associated io_service.

This implies that the handler must not be called directly from within the initiating function, even if the asynchronous operation completes immediately.

A bound completion handler is a handler object that contains a copy of a user-supplied handler, where the user-supplied handler accepts one or more arguments. The bound completion handler does not accept any arguments, and contains values to be passed as arguments to the user-supplied handler. The bound completion handler forwards the asio_handler_allocate(), asio_handler_deallocate(), and asio_handler_invoke() calls to the corresponding functions for the user-supplied handler. A bound completion handler meets the requirements for a completion handler.

For example, a bound completion handler for a ReadHandler may be implemented as follows:

template<class ReadHandler>
struct bound_read_handler
{
  bound_read_handler(ReadHandler handler, const error_code& ec, size_t s)
    : handler_(handler), ec_(ec), s_(s)
  {
  }

  void operator()()
  {
    handler_(ec_, s_);
  }

  ReadHandler handler_;
  const error_code ec_;
  const size_t s_;
};

template<class ReadHandler>
void* asio_handler_allocate(size_t size,
                            bound_read_handler<ReadHandler>* this_handler)
{
  using boost::asio::asio_handler_allocate;
  return asio_handler_allocate(size, &this_handler->handler_);
}

template<class ReadHandler>
void asio_handler_deallocate(void* pointer, std::size_t size,
                             bound_read_handler<ReadHandler>* this_handler)
{
  using boost::asio::asio_handler_deallocate;
  asio_handler_deallocate(pointer, size, &this_handler->handler_);
}

template<class F, class ReadHandler>
void asio_handler_invoke(const F& f,
                         bound_read_handler<ReadHandler>* this_handler)
{
  using boost::asio::asio_handler_invoke;
  asio_handler_invoke(f, &this_handler->handler_);
}

If the thread that initiates an asynchronous operation terminates before the associated handler is invoked, the behaviour is implementation-defined. Specifically, on Windows versions prior to Vista, unfinished operations are cancelled when the initiating thread exits.

The handler argument to an initiating function defines a handler identity. That is, the original handler argument and any copies of the handler argument will be considered equivalent. If the implementation needs to allocate storage for an asynchronous operation, the implementation will perform asio_handler_allocate(size, &h), where size is the required size in bytes, and h is the handler. The implementation will perform asio_handler_deallocate(p, size, &h), where p is a pointer to the storage, to deallocate the storage prior to the invocation of the handler via asio_handler_invoke. Multiple storage blocks may be allocated for a single asynchronous operation.

Return type of an initiating function

By default, initiating functions return void. This is always the case when the handler is a function pointer, C++11 lambda, or a function object produced by boost::bind or std::bind.

For other types, the return type may be customised via a two-step process:

  1. A specialisation of the handler_type template, which is used to determine the true handler type based on the asynchronous operation's handler's signature.
  2. A specialisation of the async_result template, which is used both to determine the return type and to extract the return value from the handler.

These two templates have been specialised to provide support for stackful coroutines and the C++11 std::future class.

As an example, consider what happens when enabling std::future support by using the boost::asio::use_future special value, as in:

std::future<std::size_t> length =
  my_socket.async_read_some(my_buffer, boost::asio::use_future);

When a handler signature has the form:

void handler(error_code ec, result_type result);

the initiating function returns a std::future templated on result_type. In the above async_read_some example, this is std::size_t. If the asynchronous operation fails, the error_code is converted into a system_error exception and passed back to the caller through the future.

Where a handler signature has the form:

void handler(error_code ec);

the initiating function instead returns std::future<void>.

An accept handler must meet the requirements for a handler. A value h of an accept handler class should work correctly in the expression h(ec), where ec is an lvalue of type const error_code.

Examples

A free function as an accept handler:

void accept_handler(
    const boost::system::error_code& ec)
{
  ...
}

An accept handler function object:

struct accept_handler
{
  ...
  void operator()(
      const boost::system::error_code& ec)
  {
    ...
  }
  ...
};

A non-static class member function adapted to an accept handler using bind():

void my_class::accept_handler(
    const boost::system::error_code& ec)
{
  ...
}
...
acceptor.async_accept(...,
    boost::bind(&my_class::accept_handler,
      this, boost::asio::placeholders::error));

In the table below, a denotes an asynchronous random access read device object, o denotes an offset of type boost::uint64_t, mb denotes an object satisfying mutable buffer sequence requirements, and h denotes an object satisfying read handler requirements.

Table 7.1. Buffer-oriented asynchronous random-access read device requirements

operation

type

semantics, pre/post-conditions

a.get_io_service();

io_service&

Returns the io_service object through which the async_read_some_at handler h will be invoked.

a.async_read_some_at(o, mb, h);

void

Initiates an asynchronous operation to read one or more bytes of data from the device a at the offset o. The operation is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

The mutable buffer sequence mb specifies memory where the data should be placed. The async_read_some_at operation shall always fill a buffer in the sequence completely before proceeding to the next.

The implementation shall maintain one or more copies of mb until such time as the read operation no longer requires access to the memory specified by the buffers in the sequence. The program must ensure the memory is valid until:

— the last copy of mb is destroyed, or

— the handler for the asynchronous read operation is invoked,

whichever comes first.

If the total size of all buffers in the sequence mb is 0, the asynchronous read operation shall complete immediately and pass 0 as the argument to the handler that specifies the number of bytes read.


In the table below, a denotes an asynchronous write stream object, o denotes an offset of type boost::uint64_t, cb denotes an object satisfying constant buffer sequence requirements, and h denotes an object satisfying write handler requirements.

Table 7.2. Buffer-oriented asynchronous random-access write device requirements

operation

type

semantics, pre/post-conditions

a.get_io_service();

io_service&

Returns the io_service object through which the async_write_some_at handler h will be invoked.

a.async_write_some_at(o, cb, h);

void

Initiates an asynchronous operation to write one or more bytes of data to the device a at offset o. The operation is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

The constant buffer sequence cb specifies memory where the data to be written is located. The async_write_some_at operation shall always write a buffer in the sequence completely before proceeding to the next.

The implementation shall maintain one or more copies of cb until such time as the write operation no longer requires access to the memory specified by the buffers in the sequence. The program must ensure the memory is valid until:

— the last copy of cb is destroyed, or

— the handler for the asynchronous write operation is invoked,

whichever comes first.

If the total size of all buffers in the sequence cb is 0, the asynchronous write operation shall complete immediately and pass 0 as the argument to the handler that specifies the number of bytes written.


In the table below, a denotes an asynchronous read stream object, mb denotes an object satisfying mutable buffer sequence requirements, and h denotes an object satisfying read handler requirements.

Table 7.3. Buffer-oriented asynchronous read stream requirements

operation

type

semantics, pre/post-conditions

a.get_io_service();

io_service&

Returns the io_service object through which the async_read_some handler h will be invoked.

a.async_read_some(mb, h);

void

Initiates an asynchronous operation to read one or more bytes of data from the stream a. The operation is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

The mutable buffer sequence mb specifies memory where the data should be placed. The async_read_some operation shall always fill a buffer in the sequence completely before proceeding to the next.

The implementation shall maintain one or more copies of mb until such time as the read operation no longer requires access to the memory specified by the buffers in the sequence. The program must ensure the memory is valid until:

— the last copy of mb is destroyed, or

— the handler for the asynchronous read operation is invoked,

whichever comes first.

If the total size of all buffers in the sequence mb is 0, the asynchronous read operation shall complete immediately and pass 0 as the argument to the handler that specifies the number of bytes read.


In the table below, a denotes an asynchronous write stream object, cb denotes an object satisfying constant buffer sequence requirements, and h denotes an object satisfying write handler requirements.

Table 7.4. Buffer-oriented asynchronous write stream requirements

operation

type

semantics, pre/post-conditions

a.get_io_service();

io_service&

Returns the io_service object through which the async_write_some handler h will be invoked.

a.async_write_some(cb, h);

void

Initiates an asynchronous operation to write one or more bytes of data to the stream a. The operation is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

The constant buffer sequence cb specifies memory where the data to be written is located. The async_write_some operation shall always write a buffer in the sequence completely before proceeding to the next.

The implementation shall maintain one or more copies of cb until such time as the write operation no longer requires access to the memory specified by the buffers in the sequence. The program must ensure the memory is valid until:

— the last copy of cb is destroyed, or

— the handler for the asynchronous write operation is invoked,

whichever comes first.

If the total size of all buffers in the sequence cb is 0, the asynchronous write operation shall complete immediately and pass 0 as the argument to the handler that specifies the number of bytes written.


A buffered handshake handler must meet the requirements for a handler. A value h of a buffered handshake handler class should work correctly in the expression h(ec, s), where ec is an lvalue of type const error_code and s is an lvalue of type const size_t.

Examples

A free function as a buffered handshake handler:

void handshake_handler(
    const boost::system::error_code& ec,
    std::size_t bytes_transferred)
{
  ...
}

A buffered handshake handler function object:

struct handshake_handler
{
  ...
  void operator()(
      const boost::system::error_code& ec,
      std::size_t bytes_transferred)
  {
    ...
  }
  ...
};

A non-static class member function adapted to a buffered handshake handler using bind():

void my_class::handshake_handler(
    const boost::system::error_code& ec,
    std::size_t bytes_transferred)
{
  ...
}
...
socket.async_handshake(...,
    boost::bind(&my_class::handshake_handler,
      this, boost::asio::placeholders::error,
      boost::asio::placeholders::bytes_transferred));

A completion handler must meet the requirements for a handler. A value h of a completion handler class should work correctly in the expression h().

Examples

A free function as a completion handler:

void completion_handler()
{
  ...
}

A completion handler function object:

struct completion_handler
{
  ...
  void operator()()
  {
    ...
  }
  ...
};

A non-static class member function adapted to a completion handler using bind():

void my_class::completion_handler()
{
  ...
}
...
my_io_service.post(boost::bind(&my_class::completion_handler, this));

A composed connect handler must meet the requirements for a handler. A value h of a composed connect handler class should work correctly in the expression h(ec, i), where ec is an lvalue of type const error_code and i is an lvalue of the type Iterator used in the corresponding connect() or async_connect()` function.

Examples

A free function as a composed connect handler:

void connect_handler(
    const boost::system::error_code& ec,
    boost::asio::ip::tcp::resolver::iterator iterator)
{
  ...
}

A composed connect handler function object:

struct connect_handler
{
  ...
  template <typename Iterator>
  void operator()(
      const boost::system::error_code& ec,
      Iterator iterator)
  {
    ...
  }
  ...
};

A non-static class member function adapted to a composed connect handler using bind():

void my_class::connect_handler(
    const boost::system::error_code& ec,
    boost::asio::ip::tcp::resolver::iterator iterator)
{
  ...
}
...
boost::asio::async_connect(...,
    boost::bind(&my_class::connect_handler,
      this, boost::asio::placeholders::error,
      boost::asio::placeholders::iterator));

A connect handler must meet the requirements for a handler. A value h of a connect handler class should work correctly in the expression h(ec), where ec is an lvalue of type const error_code.

Examples

A free function as a connect handler:

void connect_handler(
    const boost::system::error_code& ec)
{
  ...
}

A connect handler function object:

struct connect_handler
{
  ...
  void operator()(
      const boost::system::error_code& ec)
  {
    ...
  }
  ...
};

A non-static class member function adapted to a connect handler using bind():

void my_class::connect_handler(
    const boost::system::error_code& ec)
{
  ...
}
...
socket.async_connect(...,
    boost::bind(&my_class::connect_handler,
      this, boost::asio::placeholders::error));

In the table below, X denotes a class containing objects of type T, a denotes a value of type X and u denotes an identifier.

Table 7.5. ConstBufferSequence requirements

expression

return type

assertion/note
pre/post-condition

X::value_type

T

T meets the requirements for ConvertibleToConstBuffer.

X::const_iterator

iterator type pointing to T

const_iterator meets the requirements for bidirectional iterators (C++ Std, 24.1.4).

X(a);

post: equal_const_buffer_seq(a, X(a)) where the binary predicate equal_const_buffer_seq is defined as

bool equal_const_buffer_seq(
  const X& x1, const X& x2)
{
  return
    distance(x1.begin(), x1.end())
      == distance(x2.begin(), x2.end())
        && equal(x1.begin(), x1.end(),
                 x2.begin(), equal_buffer);
}

and the binary predicate equal_buffer is defined as

bool equal_buffer(
  const X::value_type& v1,
  const X::value_type& v2)
{
  const_buffer b1(v1);
  const_buffer b2(v2);
  return
    buffer_cast<const void*>(b1)
      == buffer_cast<const void*>(b2)
        && buffer_size(b1) == buffer_size(b2);
}

X u(a);

post:

distance(a.begin(), a.end())
  == distance(u.begin(), u.end())
    && equal(a.begin(), a.end(),
             u.begin(), equal_buffer)

where the binary predicate equal_buffer is defined as

bool equal_buffer(
  const X::value_type& v1,
  const X::value_type& v2)
{
  const_buffer b1(v1);
  const_buffer b2(v2);
  return
    buffer_cast<const void*>(b1)
      == buffer_cast<const void*>(b2)
        && buffer_size(b1) == buffer_size(b2);
}

(&a)->~X();

void

note: the destructor is applied to every element of a; all the memory is deallocated.

a.begin();

const_iterator or convertible to const_iterator

a.end();

const_iterator or convertible to const_iterator


A type that meets the requirements for convertibility to a const buffer must meet the requirements of CopyConstructible types (C++ Std, 20.1.3), and the requirements of Assignable types (C++ Std, 23.1).

In the table below, X denotes a class meeting the requirements for convertibility to a const buffer, a and b denote values of type X, and u, v and w denote identifiers.

Table 7.6. ConvertibleToConstBuffer requirements

expression

postcondition

const_buffer u(a);
const_buffer v(a);

buffer_cast<const void*>(u) == buffer_cast<const void*>(v)
  && buffer_size(u) == buffer_size(v)

const_buffer u(a);
const_buffer v = a;

buffer_cast<const void*>(u) == buffer_cast<const void*>(v)
  && buffer_size(u) == buffer_size(v)

const_buffer u(a);
const_buffer v; v = a;

buffer_cast<const void*>(u) == buffer_cast<const void*>(v)
  && buffer_size(u) == buffer_size(v)

const_buffer u(a);
const X& v = a;
const_buffer w(v);

buffer_cast<const void*>(u) == buffer_cast<const void*>(w)
  && buffer_size(u) == buffer_size(w)

const_buffer u(a);
X v(a);
const_buffer w(v);

buffer_cast<const void*>(u) == buffer_cast<const void*>(w)
  && buffer_size(u) == buffer_size(w)

const_buffer u(a);
X v = a;
const_buffer w(v);

buffer_cast<const void*>(u) == buffer_cast<const void*>(w)
  && buffer_size(u) == buffer_size(w)

const_buffer u(a);
X v(b); v = a;
const_buffer w(v);

buffer_cast<const void*>(u) == buffer_cast<const void*>(w)
  && buffer_size(u) == buffer_size(w)


A type that meets the requirements for convertibility to a mutable buffer must meet the requirements of CopyConstructible types (C++ Std, 20.1.3), and the requirements of Assignable types (C++ Std, 23.1).

In the table below, X denotes a class meeting the requirements for convertibility to a mutable buffer, a and b denote values of type X, and u, v and w denote identifiers.

Table 7.7. ConvertibleToMutableBuffer requirements

expression

postcondition

mutable_buffer u(a);
mutable_buffer v(a);

buffer_cast<void*>(u) == buffer_cast<void*>(v)
  && buffer_size(u) == buffer_size(v)

mutable_buffer u(a);
mutable_buffer v = a;

buffer_cast<void*>(u) == buffer_cast<void*>(v)
  && buffer_size(u) == buffer_size(v)

mutable_buffer u(a);
mutable_buffer v; v = a;

buffer_cast<void*>(u) == buffer_cast<void*>(v)
  && buffer_size(u) == buffer_size(v)

mutable_buffer u(a);
const X& v = a;
mutable_buffer w(v);

buffer_cast<void*>(u) == buffer_cast<void*>(w)
  && buffer_size(u) == buffer_size(w)

mutable_buffer u(a);
X v(a);
mutable_buffer w(v);

buffer_cast<void*>(u) == buffer_cast<void*>(w)
  && buffer_size(u) == buffer_size(w)

mutable_buffer u(a);
X v = a;
mutable_buffer w(v);

buffer_cast<void*>(u) == buffer_cast<void*>(w)
  && buffer_size(u) == buffer_size(w)

mutable_buffer u(a);
X v(b); v = a;
mutable_buffer w(v);

buffer_cast<void*>(u) == buffer_cast<void*>(w)
  && buffer_size(u) == buffer_size(w)


A datagram socket service must meet the requirements for a socket service, as well as the additional requirements listed below.

In the table below, X denotes a datagram socket service class for protocol Protocol, a denotes a value of type X, b denotes a value of type X::implementation_type, e denotes a value of type Protocol::endpoint, ec denotes a value of type error_code, f denotes a value of type socket_base::message_flags, mb denotes a value satisfying mutable buffer sequence requirements, rh denotes a value meeting ReadHandler requirements, cb denotes a value satisfying constant buffer sequence requirements, and wh denotes a value meeting WriteHandler requirements.

Table 7.8. DatagramSocketService requirements

expression

return type

assertion/note
pre/post-condition

a.receive(b, mb, f, ec);

size_t

pre: a.is_open(b).

Reads one or more bytes of data from a connected socket b.

The mutable buffer sequence mb specifies memory where the data should be placed. The operation shall always fill a buffer in the sequence completely before proceeding to the next.

If successful, returns the number of bytes read. Otherwise returns 0.

a.async_receive(b, mb, f, rh);

void

pre: a.is_open(b).

Initiates an asynchronous operation to read one or more bytes of data from a connected socket b. The operation is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

The mutable buffer sequence mb specifies memory where the data should be placed. The operation shall always fill a buffer in the sequence completely before proceeding to the next.

The implementation shall maintain one or more copies of mb until such time as the read operation no longer requires access to the memory specified by the buffers in the sequence. The program must ensure the memory is valid until:

— the last copy of mb is destroyed, or

— the handler for the asynchronous operation is invoked,

whichever comes first.

If the operation completes successfully, the ReadHandler object rh is invoked with the number of bytes transferred. Otherwise it is invoked with 0.

a.receive_from(b, mb, e, f, ec);

size_t

pre: a.is_open(b).

Reads one or more bytes of data from an unconnected socket b.

The mutable buffer sequence mb specifies memory where the data should be placed. The operation shall always fill a buffer in the sequence completely before proceeding to the next.

If successful, returns the number of bytes read. Otherwise returns 0.

a.async_receive_from(b, mb, e, f, rh);

void

pre: a.is_open(b).

Initiates an asynchronous operation to read one or more bytes of data from an unconnected socket b. The operation is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

The mutable buffer sequence mb specifies memory where the data should be placed. The operation shall always fill a buffer in the sequence completely before proceeding to the next.

The implementation shall maintain one or more copies of mb until such time as the read operation no longer requires access to the memory specified by the buffers in the sequence. The program must ensure the memory is valid until:

— the last copy of mb is destroyed, or

— the handler for the asynchronous operation is invoked,

whichever comes first.

The program must ensure the object e is valid until the handler for the asynchronous operation is invoked.

If the operation completes successfully, the ReadHandler object rh is invoked with the number of bytes transferred. Otherwise it is invoked with 0.

a.send(b, cb, f, ec);

size_t

pre: a.is_open(b).

Writes one or more bytes of data to a connected socket b.

The constant buffer sequence cb specifies memory where the data to be written is located. The operation shall always write a buffer in the sequence completely before proceeding to the next.

If successful, returns the number of bytes written. Otherwise returns 0.

a.async_send(b, cb, f, wh);

void

pre: a.is_open(b).

Initiates an asynchronous operation to write one or more bytes of data to a connected socket b. The operation is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

The constant buffer sequence cb specifies memory where the data to be written is located. The operation shall always write a buffer in the sequence completely before proceeding to the next.

The implementation shall maintain one or more copies of cb until such time as the write operation no longer requires access to the memory specified by the buffers in the sequence. The program must ensure the memory is valid until:

— the last copy of cb is destroyed, or

— the handler for the asynchronous operation is invoked,

whichever comes first.

If the operation completes successfully, the WriteHandler object wh is invoked with the number of bytes transferred. Otherwise it is invoked with 0.

const typename Protocol::endpoint& u = e;
a.send_to(b, cb, u, f, ec);

size_t

pre: a.is_open(b).

Writes one or more bytes of data to an unconnected socket b.

The constant buffer sequence cb specifies memory where the data to be written is located. The operation shall always write a buffer in the sequence completely before proceeding to the next.

If successful, returns the number of bytes written. Otherwise returns 0.

const typename Protocol::endpoint& u = e;
a.async_send(b, cb, u, f, wh);

void

pre: a.is_open(b).

Initiates an asynchronous operation to write one or more bytes of data to an unconnected socket b. The operation is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

The constant buffer sequence cb specifies memory where the data to be written is located. The operation shall always write a buffer in the sequence completely before proceeding to the next.

The implementation shall maintain one or more copies of cb until such time as the write operation no longer requires access to the memory specified by the buffers in the sequence. The program must ensure the memory is valid until:

— the last copy of cb is destroyed, or

— the handler for the asynchronous operation is invoked,

whichever comes first.

If the operation completes successfully, the WriteHandler object wh is invoked with the number of bytes transferred. Otherwise it is invoked with 0.


A descriptor service must meet the requirements for an I/O object service with support for movability, as well as the additional requirements listed below.

In the table below, X denotes a descriptor service class, a and ao denote values of type X, b and c denote values of type X::implementation_type, n denotes a value of type X::native_handle_type, ec denotes a value of type error_code, i denotes a value meeting IoControlCommand requirements, and u and v denote identifiers.

Table 7.9. DescriptorService requirements

expression

return type

assertion/note
pre/post-condition

X::native_handle_type

The implementation-defined native representation of a descriptor. Must satisfy the requirements of CopyConstructible types (C++ Std, 20.1.3), and the requirements of Assignable types (C++ Std, 23.1).

a.construct(b);

From IoObjectService requirements.
post: !a.is_open(b).

a.destroy(b);

From IoObjectService requirements. Implicitly cancels asynchronous operations, as if by calling a.close(b, ec).

a.move_construct(b, c);

From IoObjectService requirements. The underlying native representation is moved from c to b.

a.move_assign(b, ao, c);

From IoObjectService requirements. Implicitly cancels asynchronous operations associated with b, as if by calling a.close(b, ec). Then the underlying native representation is moved from c to b.

a.assign(b, n, ec);

error_code

pre: !a.is_open(b).
post: !!ec || a.is_open(b).

a.is_open(b);

bool

const X& u = a;
const X::implementation_type& v = b;
u.is_open(v);

bool

a.close(b, ec);

error_code

If a.is_open() is true, causes any outstanding asynchronous operations to complete as soon as possible. Handlers for cancelled operations shall be passed the error code error::operation_aborted.
post: !a.is_open(b).

a.native_handle(b);

X::native_handle_type

a.cancel(b, ec);

error_code

pre: a.is_open(b).
Causes any outstanding asynchronous operations to complete as soon as possible. Handlers for cancelled operations shall be passed the error code error::operation_aborted.

a.io_control(b, i, ec);

error_code

pre: a.is_open(b).


An endpoint must meet the requirements of CopyConstructible types (C++ Std, 20.1.3), and the requirements of Assignable types (C++ Std, 23.1).

In the table below, X denotes an endpoint class, a denotes a value of type X, s denotes a size in bytes, and u denotes an identifier.

Table 7.10. Endpoint requirements

expression

type

assertion/note
pre/post-conditions

X::protocol_type

type meeting protocol requirements

X u;

X();

a.protocol();

protocol_type

a.data();

a pointer

Returns a pointer suitable for passing as the address argument to POSIX functions such as accept(), getpeername(), getsockname() and recvfrom(). The implementation shall perform a reinterpret_cast on the pointer to convert it to sockaddr*.

const X& u = a; u.data();

a pointer

Returns a pointer suitable for passing as the address argument to POSIX functions such as connect(), or as the dest_addr argument to POSIX functions such as sendto(). The implementation shall perform a reinterpret_cast on the pointer to convert it to const sockaddr*.

a.size();

size_t

Returns a value suitable for passing as the address_len argument to POSIX functions such as connect(), or as the dest_len argument to POSIX functions such as sendto(), after appropriate integer conversion has been performed.

a.resize(s);

post: a.size() == s
Passed the value contained in the address_len argument to POSIX functions such as accept(), getpeername(), getsockname() and recvfrom(), after successful completion of the function. Permitted to throw an exception if the protocol associated with the endpoint object a does not support the specified size.

a.capacity();

size_t

Returns a value suitable for passing as the address_len argument to POSIX functions such as accept(), getpeername(), getsockname() and recvfrom(), after appropriate integer conversion has been performed.


In the table below, X denotes a serial port option class, a denotes a value of X, ec denotes a value of type error_code, and s denotes a value of implementation-defined type storage (where storage is the type DCB on Windows and termios on POSIX platforms), and u denotes an identifier.

Table 7.11. GettableSerialPortOption requirements

expression

type

assertion/note
pre/post-conditions

const storage& u = s;
a.load(u, ec);

error_code

Retrieves the value of the serial port option from the storage.

If successful, sets ec such that !ec is true. If an error occurred, sets ec such that !!ec is true. Returns ec.


In the table below, X denotes a socket option class, a denotes a value of X, p denotes a value that meets the protocol requirements, and u denotes an identifier.

Table 7.12. GettableSocketOption requirements

expression

type

assertion/note
pre/post-conditions

a.level(p);

int

Returns a value suitable for passing as the level argument to POSIX getsockopt() (or equivalent).

a.name(p);

int

Returns a value suitable for passing as the option_name argument to POSIX getsockopt() (or equivalent).

a.data(p);

a pointer, convertible to void*

Returns a pointer suitable for passing as the option_value argument to POSIX getsockopt() (or equivalent).

a.size(p);

size_t

Returns a value suitable for passing as the option_len argument to POSIX getsockopt() (or equivalent), after appropriate integer conversion has been performed.

a.resize(p, s);

post: a.size(p) == s.
Passed the value contained in the option_len argument to POSIX getsockopt() (or equivalent) after successful completion of the function. Permitted to throw an exception if the socket option object a does not support the specified size.


A handler must meet the requirements of CopyConstructible types (C++ Std, 20.1.3).

In the table below, X denotes a handler class, h denotes a value of X, p denotes a pointer to a block of allocated memory of type void*, s denotes the size for a block of allocated memory, and f denotes a function object taking no arguments.

Table 7.13. Handler requirements

expression

return type

assertion/note
pre/post-conditions

using boost::asio::asio_handler_allocate;
asio_handler_allocate(s, &h);

void*

Returns a pointer to a block of memory of size s. The pointer must satisfy the same alignment requirements as a pointer returned by ::operator new(). Throws bad_alloc on failure.

The asio_handler_allocate() function is located using argument-dependent lookup. The function boost::asio::asio_handler_allocate() serves as a default if no user-supplied function is available.

using boost::asio::asio_handler_deallocate;
asio_handler_deallocate(p, s, &h);

Frees a block of memory associated with a pointer p, of at least size s, that was previously allocated using asio_handler_allocate().

The asio_handler_deallocate() function is located using argument-dependent lookup. The function boost::asio::asio_handler_deallocate() serves as a default if no user-supplied function is available.

using boost::asio::asio_handler_invoke;
asio_handler_invoke(f, &h);

Causes the function object f to be executed as if by calling f().

The asio_handler_invoke() function is located using argument-dependent lookup. The function boost::asio::asio_handler_invoke() serves as a default if no user-supplied function is available.


A handle service must meet the requirements for an I/O object service with support for movability, as well as the additional requirements listed below.

In the table below, X denotes a handle service class, a and ao denote values of type X, b and c denote values of type X::implementation_type, n denotes a value of type X::native_handle_type, ec denotes a value of type error_code, and u and v denote identifiers.

Table 7.14. HandleService requirements

expression

return type

assertion/note
pre/post-condition

X::native_handle_type

The implementation-defined native representation of a handle. Must satisfy the requirements of CopyConstructible types (C++ Std, 20.1.3), and the requirements of Assignable types (C++ Std, 23.1).

a.construct(b);

From IoObjectService requirements.
post: !a.is_open(b).

a.destroy(b);

From IoObjectService requirements. Implicitly cancels asynchronous operations, as if by calling a.close(b, ec).

a.move_construct(b, c);

From IoObjectService requirements. The underlying native representation is moved from c to b.

a.move_assign(b, ao, c);

From IoObjectService requirements. Implicitly cancels asynchronous operations associated with b, as if by calling a.close(b, ec). Then the underlying native representation is moved from c to b.

a.assign(b, n, ec);

error_code

pre: !a.is_open(b).
post: !!ec || a.is_open(b).

a.is_open(b);

bool

const X& u = a;
const X::implementation_type& v = b;
u.is_open(v);

bool

a.close(b, ec);

error_code

If a.is_open() is true, causes any outstanding asynchronous operations to complete as soon as possible. Handlers for cancelled operations shall be passed the error code error::operation_aborted.
post: !a.is_open(b).

a.native_handle(b);

X::native_handle_type

a.cancel(b, ec);

error_code

pre: a.is_open(b).
Causes any outstanding asynchronous operations to complete as soon as possible. Handlers for cancelled operations shall be passed the error code error::operation_aborted.


A handshake handler must meet the requirements for a handler. A value h of a handshake handler class should work correctly in the expression h(ec), where ec is an lvalue of type const error_code.

Examples

A free function as a handshake handler:

void handshake_handler(
    const boost::system::error_code& ec)
{
  ...
}

A handshake handler function object:

struct handshake_handler
{
  ...
  void operator()(
      const boost::system::error_code& ec)
  {
    ...
  }
  ...
};

A non-static class member function adapted to a handshake handler using bind():

void my_class::handshake_handler(
    const boost::system::error_code& ec)
{
  ...
}
...
ssl_stream.async_handshake(...,
    boost::bind(&my_class::handshake_handler,
      this, boost::asio::placeholders::error));

An internet protocol must meet the requirements for a protocol as well as the additional requirements listed below.

In the table below, X denotes an internet protocol class, a denotes a value of type X, and b denotes a value of type X.

Table 7.15. InternetProtocol requirements

expression

return type

assertion/note
pre/post-conditions

X::resolver

ip::basic_resolver<X>

The type of a resolver for the protocol.

X::v4()

X

Returns an object representing the IP version 4 protocol.

X::v6()

X

Returns an object representing the IP version 6 protocol.

a == b

convertible to bool

Returns whether two protocol objects are equal.

a != b

convertible to bool

Returns !(a == b).


In the table below, X denotes an I/O control command class, a denotes a value of X, and u denotes an identifier.

Table 7.16. IoControlCommand requirements

expression

type

assertion/note
pre/post-conditions

a.name();

int

Returns a value suitable for passing as the request argument to POSIX ioctl() (or equivalent).

a.data();

a pointer, convertible to void*


An I/O object service must meet the requirements for a service, as well as the requirements listed below.

In the table below, X denotes an I/O object service class, a and ao denote values of type X, b and c denote values of type X::implementation_type, and u denotes an identifier.

Table 7.17. IoObjectService requirements

expression

return type

assertion/note
pre/post-condition

X::implementation_type

X::implementation_type u;

note: X::implementation_type has a public default constructor and destructor.

a.construct(b);

a.destroy(b);

note: destroy() will only be called on a value that has previously been initialised with construct() or move_construct().

a.move_construct(b, c);

note: only required for I/O objects that support movability.

a.move_assign(b, ao, c);

note: only required for I/O objects that support movability.


In the table below, X denotes a class containing objects of type T, a denotes a value of type X and u denotes an identifier.

Table 7.18. MutableBufferSequence requirements

expression

return type

assertion/note
pre/post-condition

X::value_type

T

T meets the requirements for ConvertibleToMutableBuffer.

X::const_iterator

iterator type pointing to T

const_iterator meets the requirements for bidirectional iterators (C++ Std, 24.1.4).

X(a);

post: equal_mutable_buffer_seq(a, X(a)) where the binary predicate equal_mutable_buffer_seq is defined as

bool equal_mutable_buffer_seq(
  const X& x1, const X& x2)
{
  return
    distance(x1.begin(), x1.end())
      == distance(x2.begin(), x2.end())
        && equal(x1.begin(), x1.end(),
                 x2.begin(), equal_buffer);
}

and the binary predicate equal_buffer is defined as

bool equal_buffer(
  const X::value_type& v1,
  const X::value_type& v2)
{
  mutable_buffer b1(v1);
  mutable_buffer b2(v2);
  return
    buffer_cast<const void*>(b1)
      == buffer_cast<const void*>(b2)
        && buffer_size(b1) == buffer_size(b2);
}

X u(a);

post:

distance(a.begin(), a.end())
  == distance(u.begin(), u.end())
    && equal(a.begin(), a.end(),
             u.begin(), equal_buffer)

where the binary predicate equal_buffer is defined as

bool equal_buffer(
  const X::value_type& v1,
  const X::value_type& v2)
{
  mutable_buffer b1(v1);
  mutable_buffer b2(v2);
  return
    buffer_cast<const void*>(b1)
      == buffer_cast<const void*>(b2)
        && buffer_size(b1) == buffer_size(b2);
}

(&a)->~X();

void

note: the destructor is applied to every element of a; all the memory is deallocated.

a.begin();

const_iterator or convertible to const_iterator

a.end();

const_iterator or convertible to const_iterator


An object handle service must meet the requirements for a handle service, as well as the additional requirements listed below.

In the table below, X denotes an object handle service class, a denotes a value of type X, b denotes a value of type X::implementation_type, ec denotes a value of type error_code, and wh denotes a value meeting WaitHandler requirements.

Table 7.19. ObjectHandleService requirements

expression

return type

assertion/note
pre/post-condition

a.wait(b, ec);

error_code

pre: a.is_open(b).

Synchronously waits for the object represented by handle b to become signalled.

a.async_wait(b, wh);

void

pre: a.is_open(b).

Initiates an asynchronous operation to wait for the object represented by handle b to become signalled. The operation is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.


A protocol must meet the requirements of CopyConstructible types (C++ Std, 20.1.3), and the requirements of Assignable types (C++ Std, 23.1).

In the table below, X denotes a protocol class, and a denotes a value of X.

Table 7.20. Protocol requirements

expression

return type

assertion/note
pre/post-conditions

X::endpoint

type meeting endpoint requirements

a.family()

int

Returns a value suitable for passing as the domain argument to POSIX socket() (or equivalent).

a.type()

int

Returns a value suitable for passing as the type argument to POSIX socket() (or equivalent).

a.protocol()

int

Returns a value suitable for passing as the protocol argument to POSIX socket() (or equivalent).


A random access handle service must meet the requirements for a handle service, as well as the additional requirements listed below.

In the table below, X denotes a random access handle service class, a denotes a value of type X, b denotes a value of type X::implementation_type, ec denotes a value of type error_code, o denotes an offset of type boost::uint64_t, mb denotes a value satisfying mutable buffer sequence requirements, rh denotes a value meeting ReadHandler requirements, cb denotes a value satisfying constant buffer sequence requirements, and wh denotes a value meeting WriteHandler requirements.

Table 7.21. RandomAccessHandleService requirements

expression

return type

assertion/note
pre/post-condition

a.read_some_at(b, o, mb, ec);

size_t

pre: a.is_open(b).

Reads one or more bytes of data from a handle b at offset o.

The mutable buffer sequence mb specifies memory where the data should be placed. The operation shall always fill a buffer in the sequence completely before proceeding to the next.

If successful, returns the number of bytes read. Otherwise returns 0. If the total size of all buffers in the sequence mb is 0, the function shall return 0 immediately.

a.async_read_some_at(b, o, mb, rh);

void

pre: a.is_open(b).

Initiates an asynchronous operation to read one or more bytes of data from a handle b at offset o. The operation is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

The mutable buffer sequence mb specifies memory where the data should be placed. The operation shall always fill a buffer in the sequence completely before proceeding to the next.

The implementation shall maintain one or more copies of mb until such time as the read operation no longer requires access to the memory specified by the buffers in the sequence. The program must ensure the memory is valid until:

— the last copy of mb is destroyed, or

— the handler for the asynchronous operation is invoked,

whichever comes first. If the total size of all buffers in the sequence mb is 0, the asynchronous read operation shall complete immediately and pass 0 as the argument to the handler that specifies the number of bytes read.

If the operation completes successfully, the ReadHandler object rh is invoked with the number of bytes transferred. Otherwise it is invoked with 0.

a.write_some_at(b, o, cb, ec);

size_t

pre: a.is_open(b).

Writes one or more bytes of data to a handle b at offset o.

The constant buffer sequence cb specifies memory where the data to be written is located. The operation shall always write a buffer in the sequence completely before proceeding to the next.

If successful, returns the number of bytes written. Otherwise returns 0. If the total size of all buffers in the sequence cb is 0, the function shall return 0 immediately.

a.async_write_some_at(b, o, cb, wh);

void

pre: a.is_open(b).

Initiates an asynchronous operation to write one or more bytes of data to a handle b at offset o. The operation is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

The constant buffer sequence cb specifies memory where the data to be written is located. The operation shall always write a buffer in the sequence completely before proceeding to the next.

The implementation shall maintain one or more copies of cb until such time as the write operation no longer requires access to the memory specified by the buffers in the sequence. The program must ensure the memory is valid until:

— the last copy of cb is destroyed, or

— the handler for the asynchronous operation is invoked,

whichever comes first. If the total size of all buffers in the sequence cb is 0, the asynchronous operation shall complete immediately and pass 0 as the argument to the handler that specifies the number of bytes read.

If the operation completes successfully, the WriteHandler object wh is invoked with the number of bytes transferred. Otherwise it is invoked with 0.


A raw socket service must meet the requirements for a socket service, as well as the additional requirements listed below.

In the table below, X denotes a raw socket service class for protocol Protocol, a denotes a value of type X, b denotes a value of type X::implementation_type, e denotes a value of type Protocol::endpoint, ec denotes a value of type error_code, f denotes a value of type socket_base::message_flags, mb denotes a value satisfying mutable buffer sequence requirements, rh denotes a value meeting ReadHandler requirements, cb denotes a value satisfying constant buffer sequence requirements, and wh denotes a value meeting WriteHandler requirements.

Table 7.22. RawSocketService requirements

expression

return type

assertion/note
pre/post-condition

a.receive(b, mb, f, ec);

size_t

pre: a.is_open(b).

Reads one or more bytes of data from a connected socket b.

The mutable buffer sequence mb specifies memory where the data should be placed. The operation shall always fill a buffer in the sequence completely before proceeding to the next.

If successful, returns the number of bytes read. Otherwise returns 0.

a.async_receive(b, mb, f, rh);

void

pre: a.is_open(b).

Initiates an asynchronous operation to read one or more bytes of data from a connected socket b. The operation is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

The mutable buffer sequence mb specifies memory where the data should be placed. The operation shall always fill a buffer in the sequence completely before proceeding to the next.

The implementation shall maintain one or more copies of mb until such time as the read operation no longer requires access to the memory specified by the buffers in the sequence. The program must ensure the memory is valid until:

— the last copy of mb is destroyed, or

— the handler for the asynchronous operation is invoked,

whichever comes first.

If the operation completes successfully, the ReadHandler object rh is invoked with the number of bytes transferred. Otherwise it is invoked with 0.

a.receive_from(b, mb, e, f, ec);

size_t

pre: a.is_open(b).

Reads one or more bytes of data from an unconnected socket b.

The mutable buffer sequence mb specifies memory where the data should be placed. The operation shall always fill a buffer in the sequence completely before proceeding to the next.

If successful, returns the number of bytes read. Otherwise returns 0.

a.async_receive_from(b, mb, e, f, rh);

void

pre: a.is_open(b).

Initiates an asynchronous operation to read one or more bytes of data from an unconnected socket b. The operation is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

The mutable buffer sequence mb specifies memory where the data should be placed. The operation shall always fill a buffer in the sequence completely before proceeding to the next.

The implementation shall maintain one or more copies of mb until such time as the read operation no longer requires access to the memory specified by the buffers in the sequence. The program must ensure the memory is valid until:

— the last copy of mb is destroyed, or

— the handler for the asynchronous operation is invoked,

whichever comes first.

The program must ensure the object e is valid until the handler for the asynchronous operation is invoked.

If the operation completes successfully, the ReadHandler object rh is invoked with the number of bytes transferred. Otherwise it is invoked with 0.

a.send(b, cb, f, ec);

size_t

pre: a.is_open(b).

Writes one or more bytes of data to a connected socket b.

The constant buffer sequence cb specifies memory where the data to be written is located. The operation shall always write a buffer in the sequence completely before proceeding to the next.

If successful, returns the number of bytes written. Otherwise returns 0.

a.async_send(b, cb, f, wh);

void

pre: a.is_open(b).

Initiates an asynchronous operation to write one or more bytes of data to a connected socket b. The operation is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

The constant buffer sequence cb specifies memory where the data to be written is located. The operation shall always write a buffer in the sequence completely before proceeding to the next.

The implementation shall maintain one or more copies of cb until such time as the write operation no longer requires access to the memory specified by the buffers in the sequence. The program must ensure the memory is valid until:

— the last copy of cb is destroyed, or

— the handler for the asynchronous operation is invoked,

whichever comes first.

If the operation completes successfully, the WriteHandler object wh is invoked with the number of bytes transferred. Otherwise it is invoked with 0.

const typename Protocol::endpoint& u = e;
a.send_to(b, cb, u, f, ec);

size_t

pre: a.is_open(b).

Writes one or more bytes of data to an unconnected socket b.

The constant buffer sequence cb specifies memory where the data to be written is located. The operation shall always write a buffer in the sequence completely before proceeding to the next.

If successful, returns the number of bytes written. Otherwise returns 0.

const typename Protocol::endpoint& u = e;
a.async_send(b, cb, u, f, wh);

void

pre: a.is_open(b).

Initiates an asynchronous operation to write one or more bytes of data to an unconnected socket b. The operation is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

The constant buffer sequence cb specifies memory where the data to be written is located. The operation shall always write a buffer in the sequence completely before proceeding to the next.

The implementation shall maintain one or more copies of cb until such time as the write operation no longer requires access to the memory specified by the buffers in the sequence. The program must ensure the memory is valid until:

— the last copy of cb is destroyed, or

— the handler for the asynchronous operation is invoked,

whichever comes first.

If the operation completes successfully, the WriteHandler object wh is invoked with the number of bytes transferred. Otherwise it is invoked with 0.


A read handler must meet the requirements for a handler. A value h of a read handler class should work correctly in the expression h(ec, s), where ec is an lvalue of type const error_code and s is an lvalue of type const size_t.

Examples

A free function as a read handler:

void read_handler(
    const boost::system::error_code& ec,
    std::size_t bytes_transferred)
{
  ...
}

A read handler function object:

struct read_handler
{
  ...
  void operator()(
      const boost::system::error_code& ec,
      std::size_t bytes_transferred)
  {
    ...
  }
  ...
};

A non-static class member function adapted to a read handler using bind():

void my_class::read_handler(
    const boost::system::error_code& ec,
    std::size_t bytes_transferred)
{
  ...
}
...
socket.async_read(...,
    boost::bind(&my_class::read_handler,
      this, boost::asio::placeholders::error,
      boost::asio::placeholders::bytes_transferred));

A resolve handler must meet the requirements for a handler. A value h of a resolve handler class should work correctly in the expression h(ec, i), where ec is an lvalue of type const error_code and i is an lvalue of type const ip::basic_resolver_iterator<InternetProtocol>. InternetProtocol is the template parameter of the resolver_service which is used to initiate the asynchronous operation.

Examples

A free function as a resolve handler:

void resolve_handler(
    const boost::system::error_code& ec,
    boost::asio::ip::tcp::resolver::iterator iterator)
{
  ...
}

A resolve handler function object:

struct resolve_handler
{
  ...
  void operator()(
      const boost::system::error_code& ec,
      boost::asio::ip::tcp::resolver::iterator iterator)
  {
    ...
  }
  ...
};

A non-static class member function adapted to a resolve handler using bind():

void my_class::resolve_handler(
    const boost::system::error_code& ec,
    boost::asio::ip::tcp::resolver::iterator iterator)
{
  ...
}
...
resolver.async_resolve(...,
    boost::bind(&my_class::resolve_handler,
      this, boost::asio::placeholders::error,
      boost::asio::placeholders::iterator));

A resolver service must meet the requirements for an I/O object service, as well as the additional requirements listed below.

In the table below, X denotes a resolver service class for protocol InternetProtocol, a denotes a value of type X, b denotes a value of type X::implementation_type, q denotes a value of type ip::basic_resolver_query<InternetProtocol>, e denotes a value of type ip::basic_endpoint<InternetProtocol>, ec denotes a value of type error_code, and h denotes a value meeting ResolveHandler requirements.

Table 7.23. ResolverService requirements

expression

return type

assertion/note
pre/post-condition

a.destroy(b);

From IoObjectService requirements. Implicitly cancels asynchronous resolve operations, as if by calling a.cancel(b, ec).

a.cancel(b, ec);

error_code

Causes any outstanding asynchronous resolve operations to complete as soon as possible. Handlers for cancelled operations shall be passed the error code error::operation_aborted.

a.resolve(b, q, ec);

ip::basic_resolver_iterator<
  InternetProtocol>

On success, returns an iterator i such that i != ip::basic_resolver_iterator<InternetProtocol>(). Otherwise returns ip::basic_resolver_iterator<InternetProtocol>().

a.async_resolve(b, q, h);

Initiates an asynchronous resolve operation that is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

If the operation completes successfully, the ResolveHandler object h shall be invoked with an iterator object i such that the condition i != ip::basic_resolver_iterator<InternetProtocol>() holds. Otherwise it is invoked with ip::basic_resolver_iterator<InternetProtocol>().

a.resolve(b, e, ec);

ip::basic_resolver_iterator<
  InternetProtocol>

On success, returns an iterator i such that i != ip::basic_resolver_iterator<InternetProtocol>(). Otherwise returns ip::basic_resolver_iterator<InternetProtocol>().

a.async_resolve(b, e, h);

Initiates an asynchronous resolve operation that is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

If the operation completes successfully, the ResolveHandler object h shall be invoked with an iterator object i such that the condition i != ip::basic_resolver_iterator<InternetProtocol>() holds. Otherwise it is invoked with ip::basic_resolver_iterator<InternetProtocol>().


A sequenced packet socket service must meet the requirements for a socket service, as well as the additional requirements listed below.

In the table below, X denotes a stream socket service class, a denotes a value of type X, b denotes a value of type X::implementation_type, ec denotes a value of type error_code, f denotes a value of type socket_base::message_flags, g denotes an lvalue of type socket_base::message_flags, mb denotes a value satisfying mutable buffer sequence requirements, rh denotes a value meeting ReadHandler requirements, cb denotes a value satisfying constant buffer sequence requirements, and wh denotes a value meeting WriteHandler requirements.

Table 7.24. StreamSocketService requirements

expression

return type

assertion/note
pre/post-condition

a.receive(b, mb, f, g, ec);

size_t

pre: a.is_open(b).

Reads one or more bytes of data from a connected socket b.

The mutable buffer sequence mb specifies memory where the data should be placed. The operation shall always fill a buffer in the sequence completely before proceeding to the next.

If successful, sets g to the flags associated with the received data, and returns the number of bytes read. Otherwise, sets g to 0 and returns 0.

a.async_receive(b, mb, f, g, rh);

void

pre: a.is_open(b).

Initiates an asynchronous operation to read one or more bytes of data from a connected socket b. The operation is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

The mutable buffer sequence mb specifies memory where the data should be placed. The operation shall always fill a buffer in the sequence completely before proceeding to the next.

The implementation shall maintain one or more copies of mb until such time as the read operation no longer requires access to the memory specified by the buffers in the sequence. The program must ensure the memory is valid until:

— the last copy of mb is destroyed, or

— the handler for the asynchronous operation is invoked,

whichever comes first.

If the operation completes successfully, sets g to the flags associated with the received data, then invokes the ReadHandler object rh with the number of bytes transferred. Otherwise, sets g to 0 and invokes rh with 0 bytes transferred.

a.send(b, cb, f, ec);

size_t

pre: a.is_open(b).

Writes one or more bytes of data to a connected socket b.

The constant buffer sequence cb specifies memory where the data to be written is located. The operation shall always write a buffer in the sequence completely before proceeding to the next.

If successful, returns the number of bytes written. Otherwise returns 0.

a.async_send(b, cb, f, wh);

void

pre: a.is_open(b).

Initiates an asynchronous operation to write one or more bytes of data to a connected socket b. The operation is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

The constant buffer sequence cb specifies memory where the data to be written is located. The operation shall always write a buffer in the sequence completely before proceeding to the next.

The implementation shall maintain one or more copies of cb until such time as the write operation no longer requires access to the memory specified by the buffers in the sequence. The program must ensure the memory is valid until:

— the last copy of cb is destroyed, or

— the handler for the asynchronous operation is invoked,

whichever comes first.

If the operation completes successfully, the WriteHandler object wh is invoked with the number of bytes transferred. Otherwise it is invoked with 0.


A serial port service must meet the requirements for an I/O object service with support for movability, as well as the additional requirements listed below.

In the table below, X denotes a serial port service class, a and ao denote values of type X, d denotes a serial port device name of type std::string, b and c denote values of type X::implementation_type, n denotes a value of type X::native_handle_type, ec denotes a value of type error_code, s denotes a value meeting SettableSerialPortOption requirements, g denotes a value meeting GettableSerialPortOption requirements, mb denotes a value satisfying mutable buffer sequence requirements, rh denotes a value meeting ReadHandler requirements, cb denotes a value satisfying constant buffer sequence requirements, and wh denotes a value meeting WriteHandler requirements. and u and v denote identifiers.

Table 7.25. SerialPortService requirements

expression

return type

assertion/note
pre/post-condition

X::native_handle_type

The implementation-defined native representation of a serial port. Must satisfy the requirements of CopyConstructible types (C++ Std, 20.1.3), and the requirements of Assignable types (C++ Std, 23.1).

a.construct(b);

From IoObjectService requirements.
post: !a.is_open(b).

a.destroy(b);

From IoObjectService requirements. Implicitly cancels asynchronous operations, as if by calling a.close(b, ec).

a.move_construct(b, c);

From IoObjectService requirements. The underlying native representation is moved from c to b.

a.move_assign(b, ao, c);

From IoObjectService requirements. Implicitly cancels asynchronous operations associated with b, as if by calling a.close(b, ec). Then the underlying native representation is moved from c to b.

const std::string& u = d;
a.open(b, u, ec);

error_code

pre: !a.is_open(b).
post: !!ec || a.is_open(b).

a.assign(b, n, ec);

error_code

pre: !a.is_open(b).
post: !!ec || a.is_open(b).

a.is_open(b);

bool

const X& u = a;
const X::implementation_type& v = b;
u.is_open(v);

bool

a.close(b, ec);

error_code

If a.is_open() is true, causes any outstanding asynchronous operations to complete as soon as possible. Handlers for cancelled operations shall be passed the error code error::operation_aborted.
post: !a.is_open(b).

a.native_handle(b);

X::native_handle_type

a.cancel(b, ec);

error_code

pre: a.is_open(b).
Causes any outstanding asynchronous operations to complete as soon as possible. Handlers for cancelled operations shall be passed the error code error::operation_aborted.

a.set_option(b, s, ec);

error_code

pre: a.is_open(b).

a.get_option(b, g, ec);

error_code

pre: a.is_open(b).

const X& u = a;
const X::implementation_type& v = b;
u.get_option(v, g, ec);

error_code

pre: a.is_open(b).

a.send_break(b, ec);

error_code

pre: a.is_open(b).

a.read_some(b, mb, ec);

size_t

pre: a.is_open(b).

Reads one or more bytes of data from a serial port b.

The mutable buffer sequence mb specifies memory where the data should be placed. The operation shall always fill a buffer in the sequence completely before proceeding to the next.

If successful, returns the number of bytes read. Otherwise returns 0. If the total size of all buffers in the sequence mb is 0, the function shall return 0 immediately.

If the operation completes due to graceful connection closure by the peer, the operation shall fail with error::eof.

a.async_read_some(b, mb, rh);

void

pre: a.is_open(b).

Initiates an asynchronous operation to read one or more bytes of data from a serial port b. The operation is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

The mutable buffer sequence mb specifies memory where the data should be placed. The operation shall always fill a buffer in the sequence completely before proceeding to the next.

The implementation shall maintain one or more copies of mb until such time as the read operation no longer requires access to the memory specified by the buffers in the sequence. The program must ensure the memory is valid until:

— the last copy of mb is destroyed, or

— the handler for the asynchronous operation is invoked,

whichever comes first. If the total size of all buffers in the sequence mb is 0, the asynchronous read operation shall complete immediately and pass 0 as the argument to the handler that specifies the number of bytes read.

If the operation completes due to graceful connection closure by the peer, the operation shall fail with error::eof.

If the operation completes successfully, the ReadHandler object rh is invoked with the number of bytes transferred. Otherwise it is invoked with 0.

a.write_some(b, cb, ec);

size_t

pre: a.is_open(b).

Writes one or more bytes of data to a serial port b.

The constant buffer sequence cb specifies memory where the data to be written is located. The operation shall always write a buffer in the sequence completely before proceeding to the next.

If successful, returns the number of bytes written. Otherwise returns 0. If the total size of all buffers in the sequence cb is 0, the function shall return 0 immediately.

a.async_write_some(b, cb, wh);

void

pre: a.is_open(b).

Initiates an asynchronous operation to write one or more bytes of data to a serial port b. The operation is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

The constant buffer sequence cb specifies memory where the data to be written is located. The operation shall always write a buffer in the sequence completely before proceeding to the next.

The implementation shall maintain one or more copies of cb until such time as the write operation no longer requires access to the memory specified by the buffers in the sequence. The program must ensure the memory is valid until:

— the last copy of cb is destroyed, or

— the handler for the asynchronous operation is invoked,

whichever comes first. If the total size of all buffers in the sequence cb is 0, the asynchronous operation shall complete immediately and pass 0 as the argument to the handler that specifies the number of bytes read.

If the operation completes successfully, the WriteHandler object wh is invoked with the number of bytes transferred. Otherwise it is invoked with 0.


A class is a service if it is publicly derived from another service, or if it is a class derived from io_service::service and contains a publicly-accessible declaration as follows:

static io_service::id id;

All services define a one-argument constructor that takes a reference to the io_service object that owns the service. This constructor is explicit, preventing its participation in automatic conversions. For example:

class my_service : public io_service::service
{
public:
  static io_service::id id;
  explicit my_service(io_service& ios);
private:
  virtual void shutdown_service();
  ...
};

A service's shutdown_service member function must cause all copies of user-defined handler objects that are held by the service to be destroyed.

In the table below, X denotes a serial port option class, a denotes a value of X, ec denotes a value of type error_code, and s denotes a value of implementation-defined type storage (where storage is the type DCB on Windows and termios on POSIX platforms), and u denotes an identifier.

Table 7.26. SettableSerialPortOption requirements

expression

type

assertion/note
pre/post-conditions

const X& u = a;
u.store(s, ec);

error_code

Saves the value of the serial port option to the storage.

If successful, sets ec such that !ec is true. If an error occurred, sets ec such that !!ec is true. Returns ec.


In the table below, X denotes a socket option class, a denotes a value of X, p denotes a value that meets the protocol requirements, and u denotes an identifier.

Table 7.27. SettableSocketOption requirements

expression

type

assertion/note
pre/post-conditions

a.level(p);

int

Returns a value suitable for passing as the level argument to POSIX setsockopt() (or equivalent).

a.name(p);

int

Returns a value suitable for passing as the option_name argument to POSIX setsockopt() (or equivalent).

const X& u = a; u.data(p);

a pointer, convertible to const void*

Returns a pointer suitable for passing as the option_value argument to POSIX setsockopt() (or equivalent).

a.size(p);

size_t

Returns a value suitable for passing as the option_len argument to POSIX setsockopt() (or equivalent), after appropriate integer conversion has been performed.


A shutdown handler must meet the requirements for a handler. A value h of a shutdown handler class should work correctly in the expression h(ec), where ec is an lvalue of type const error_code.

Examples

A free function as a shutdown handler:

void shutdown_handler(
    const boost::system::error_code& ec)
{
  ...
}

A shutdown handler function object:

struct shutdown_handler
{
  ...
  void operator()(
      const boost::system::error_code& ec)
  {
    ...
  }
  ...
};

A non-static class member function adapted to a shutdown handler using bind():

void my_class::shutdown_handler(
    const boost::system::error_code& ec)
{
  ...
}
...
ssl_stream.async_shutdown(
    boost::bind(&my_class::shutdown_handler,
      this, boost::asio::placeholders::error));

A signal handler must meet the requirements for a handler. A value h of a signal handler class should work correctly in the expression h(ec, n), where ec is an lvalue of type const error_code and n is an lvalue of type const int.

Examples

A free function as a signal handler:

void signal_handler(
    const boost::system::error_code& ec,
    int signal_number)
{
  ...
}

A signal handler function object:

struct signal_handler
{
  ...
  void operator()(
      const boost::system::error_code& ec,
      int signal_number)
  {
    ...
  }
  ...
};

A non-static class member function adapted to a signal handler using bind():

void my_class::signal_handler(
    const boost::system::error_code& ec,
    int signal_number)
{
  ...
}
...
my_signal_set.async_wait(
    boost::bind(&my_class::signal_handler,
      this, boost::asio::placeholders::error,
      boost::asio::placeholders::signal_number));

A signal set service must meet the requirements for an I/O object service, as well as the additional requirements listed below.

In the table below, X denotes a signal set service class, a denotes a value of type X, b denotes a value of type X::implementation_type, ec denotes a value of type error_code, n denotes a value of type int, and sh denotes a value meeting SignalHandler requirements.

Table 7.28. SignalSetService requirements

expression

return type

assertion/note
pre/post-condition

a.construct(b);

From IoObjectService requirements.

a.destroy(b);

From IoObjectService requirements. Implicitly clears the registered signals as if by calling a.clear(b, ec), then implicitly cancels outstanding asynchronous operations as if by calling a.cancel(b, ec).

a.add(b, n, ec);

error_code

a.remove(b, n, ec);

error_code

a.clear(b, ec);

error_code

a.cancel(b, ec);

error_code

a.async_wait(b, sh);

void

pre: a.is_open(b).

Initiates an asynchronous operation to wait for the delivery of one of the signals registered for the signal set b. The operation is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

If the operation completes successfully, the SignalHandler object sh is invoked with the number identifying the delivered signal. Otherwise it is invoked with 0.


A socket acceptor service must meet the requirements for an I/O object service, as well as the additional requirements listed below.

In the table below, X denotes a socket acceptor service class for protocol Protocol, a and ao denote values of type X, b and c denote values of type X::implementation_type, p denotes a value of type Protocol, n denotes a value of type X::native_handle_type, e denotes a value of type Protocol::endpoint, ec denotes a value of type error_code, s denotes a value meeting SettableSocketOption requirements, g denotes a value meeting GettableSocketOption requirements, i denotes a value meeting IoControlCommand requirements, k denotes a value of type basic_socket<Protocol, SocketService> where SocketService is a type meeting socket service requirements, ah denotes a value meeting AcceptHandler requirements, and u and v denote identifiers.

Table 7.29. SocketAcceptorService requirements

expression

return type

assertion/note
pre/post-condition

X::native_handle_type

The implementation-defined native representation of a socket acceptor. Must satisfy the requirements of CopyConstructible types (C++ Std, 20.1.3), and the requirements of Assignable types (C++ Std, 23.1).

a.construct(b);

From IoObjectService requirements.
post: !a.is_open(b).

a.destroy(b);

From IoObjectService requirements. Implicitly cancels asynchronous operations, as if by calling a.close(b, ec).

a.move_construct(b, c);

From IoObjectService requirements. The underlying native representation is moved from c to b.

a.move_assign(b, ao, c);

From IoObjectService requirements. Implicitly cancels asynchronous operations associated with b, as if by calling a.close(b, ec). Then the underlying native representation is moved from c to b.

a.open(b, p, ec);

error_code

pre: !a.is_open(b).
post: !!ec || a.is_open(b).

a.assign(b, p, n, ec);

error_code

pre: !a.is_open(b).
post: !!ec || a.is_open(b).

a.is_open(b);

bool

const X& u = a;
const X::implementation_type& v = b;
u.is_open(v);

bool

a.close(b, ec);

error_code

If a.is_open() is true, causes any outstanding asynchronous operations to complete as soon as possible. Handlers for cancelled operations shall be passed the error code error::operation_aborted.
post: !a.is_open(b).

a.native_handle(b);

X::native_handle_type

a.cancel(b, ec);

error_code

pre: a.is_open(b).
Causes any outstanding asynchronous operations to complete as soon as possible. Handlers for cancelled operations shall be passed the error code error::operation_aborted.

a.set_option(b, s, ec);

error_code

pre: a.is_open(b).

a.get_option(b, g, ec);

error_code

pre: a.is_open(b).

const X& u = a;
const X::implementation_type& v = b;
u.get_option(v, g, ec);

error_code

pre: a.is_open(b).

a.io_control(b, i, ec);

error_code

pre: a.is_open(b).

const typename Protocol::endpoint& u = e;
a.bind(b, u, ec);

error_code

pre: a.is_open(b).

a.local_endpoint(b, ec);

Protocol::endpoint

pre: a.is_open(b).

const X& u = a;
const X::implementation_type& v = b;
u.local_endpoint(v, ec);

Protocol::endpoint

pre: a.is_open(b).

a.accept(b, k, &e, ec);

error_code

pre: a.is_open(b) && !k.is_open().
post: k.is_open()

a.accept(b, k, 0, ec);

error_code

pre: a.is_open(b) && !k.is_open().
post: k.is_open()

a.async_accept(b, k, &e, ah);

pre: a.is_open(b) && !k.is_open().
Initiates an asynchronous accept operation that is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

The program must ensure the objects k and e are valid until the handler for the asynchronous operation is invoked.

a.async_accept(b, k, 0, ah);

pre: a.is_open(b) && !k.is_open().
Initiates an asynchronous accept operation that is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

The program must ensure the object k is valid until the handler for the asynchronous operation is invoked.


A socket service must meet the requirements for an I/O object service with support for movability, as well as the additional requirements listed below.

In the table below, X denotes a socket service class for protocol Protocol, a and ao denote values of type X, b and c denote values of type X::implementation_type, p denotes a value of type Protocol, n denotes a value of type X::native_handle_type, e denotes a value of type Protocol::endpoint, ec denotes a value of type error_code, s denotes a value meeting SettableSocketOption requirements, g denotes a value meeting GettableSocketOption requirements, i denotes a value meeting IoControlCommand requirements, h denotes a value of type socket_base::shutdown_type, ch denotes a value meeting ConnectHandler requirements, and u and v denote identifiers.

Table 7.30. SocketService requirements

expression

return type

assertion/note
pre/post-condition

X::native_handle_type

The implementation-defined native representation of a socket. Must satisfy the requirements of CopyConstructible types (C++ Std, 20.1.3), and the requirements of Assignable types (C++ Std, 23.1).

a.construct(b);

From IoObjectService requirements.
post: !a.is_open(b).

a.destroy(b);

From IoObjectService requirements. Implicitly cancels asynchronous operations, as if by calling a.close(b, ec).

a.move_construct(b, c);

From IoObjectService requirements. The underlying native representation is moved from c to b.

a.move_assign(b, ao, c);

From IoObjectService requirements. Implicitly cancels asynchronous operations associated with b, as if by calling a.close(b, ec). Then the underlying native representation is moved from c to b.

a.open(b, p, ec);

error_code

pre: !a.is_open(b).
post: !!ec || a.is_open(b).

a.assign(b, p, n, ec);

error_code

pre: !a.is_open(b).
post: !!ec || a.is_open(b).

a.is_open(b);

bool

const X& u = a;
const X::implementation_type& v = b;
u.is_open(v);

bool

a.close(b, ec);

error_code

If a.is_open() is true, causes any outstanding asynchronous operations to complete as soon as possible. Handlers for cancelled operations shall be passed the error code error::operation_aborted.
post: !a.is_open(b).

a.native_handle(b);

X::native_handle_type

a.cancel(b, ec);

error_code

pre: a.is_open(b).
Causes any outstanding asynchronous operations to complete as soon as possible. Handlers for cancelled operations shall be passed the error code error::operation_aborted.

a.set_option(b, s, ec);

error_code

pre: a.is_open(b).

a.get_option(b, g, ec);

error_code

pre: a.is_open(b).

const X& u = a;
const X::implementation_type& v = b;
u.get_option(v, g, ec);

error_code

pre: a.is_open(b).

a.io_control(b, i, ec);

error_code

pre: a.is_open(b).

a.at_mark(b, ec);

bool

pre: a.is_open(b).

const X& u = a;
const X::implementation_type& v = b;
u.at_mark(v, ec);

bool

pre: a.is_open(b).

a.available(b, ec);

size_t

pre: a.is_open(b).

const X& u = a;
const X::implementation_type& v = b;
u.available(v, ec);

size_t

pre: a.is_open(b).

const typename Protocol::endpoint& u = e;
a.bind(b, u, ec);

error_code

pre: a.is_open(b).

a.shutdown(b, h, ec);

error_code

pre: a.is_open(b).

a.local_endpoint(b, ec);

Protocol::endpoint

pre: a.is_open(b).

const X& u = a;
const X::implementation_type& v = b;
u.local_endpoint(v, ec);

Protocol::endpoint

pre: a.is_open(b).

a.remote_endpoint(b, ec);

Protocol::endpoint

pre: a.is_open(b).

const X& u = a;
const X::implementation_type& v = b;
u.remote_endpoint(v, ec);

Protocol::endpoint

pre: a.is_open(b).

const typename Protocol::endpoint& u = e;
a.connect(b, u, ec);

error_code

pre: a.is_open(b).

const typename Protocol::endpoint& u = e;
a.async_connect(b, u, ch);

pre: a.is_open(b).
Initiates an asynchronous connect operation that is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.


A stream descriptor service must meet the requirements for a descriptor service, as well as the additional requirements listed below.

In the table below, X denotes a stream descriptor service class, a denotes a value of type X, b denotes a value of type X::implementation_type, ec denotes a value of type error_code, mb denotes a value satisfying mutable buffer sequence requirements, rh denotes a value meeting ReadHandler requirements, cb denotes a value satisfying constant buffer sequence requirements, and wh denotes a value meeting WriteHandler requirements.

Table 7.31. StreamDescriptorService requirements

expression

return type

assertion/note
pre/post-condition

a.read_some(b, mb, ec);

size_t

pre: a.is_open(b).

Reads one or more bytes of data from a descriptor b.

The mutable buffer sequence mb specifies memory where the data should be placed. The operation shall always fill a buffer in the sequence completely before proceeding to the next.

If successful, returns the number of bytes read. Otherwise returns 0. If the total size of all buffers in the sequence mb is 0, the function shall return 0 immediately.

If the operation completes due to graceful connection closure by the peer, the operation shall fail with error::eof.

a.async_read_some(b, mb, rh);

void

pre: a.is_open(b).

Initiates an asynchronous operation to read one or more bytes of data from a descriptor b. The operation is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

The mutable buffer sequence mb specifies memory where the data should be placed. The operation shall always fill a buffer in the sequence completely before proceeding to the next.

The implementation shall maintain one or more copies of mb until such time as the read operation no longer requires access to the memory specified by the buffers in the sequence. The program must ensure the memory is valid until:

— the last copy of mb is destroyed, or

— the handler for the asynchronous operation is invoked,

whichever comes first. If the total size of all buffers in the sequence mb is 0, the asynchronous read operation shall complete immediately and pass 0 as the argument to the handler that specifies the number of bytes read.

If the operation completes due to graceful connection closure by the peer, the operation shall fail with error::eof.

If the operation completes successfully, the ReadHandler object rh is invoked with the number of bytes transferred. Otherwise it is invoked with 0.

a.write_some(b, cb, ec);

size_t

pre: a.is_open(b).

Writes one or more bytes of data to a descriptor b.

The constant buffer sequence cb specifies memory where the data to be written is located. The operation shall always write a buffer in the sequence completely before proceeding to the next.

If successful, returns the number of bytes written. Otherwise returns 0. If the total size of all buffers in the sequence cb is 0, the function shall return 0 immediately.

a.async_write_some(b, cb, wh);

void

pre: a.is_open(b).

Initiates an asynchronous operation to write one or more bytes of data to a descriptor b. The operation is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

The constant buffer sequence cb specifies memory where the data to be written is located. The operation shall always write a buffer in the sequence completely before proceeding to the next.

The implementation shall maintain one or more copies of cb until such time as the write operation no longer requires access to the memory specified by the buffers in the sequence. The program must ensure the memory is valid until:

— the last copy of cb is destroyed, or

— the handler for the asynchronous operation is invoked,

whichever comes first. If the total size of all buffers in the sequence cb is 0, the asynchronous operation shall complete immediately and pass 0 as the argument to the handler that specifies the number of bytes read.

If the operation completes successfully, the WriteHandler object wh is invoked with the number of bytes transferred. Otherwise it is invoked with 0.


A stream handle service must meet the requirements for a handle service, as well as the additional requirements listed below.

In the table below, X denotes a stream handle service class, a denotes a value of type X, b denotes a value of type X::implementation_type, ec denotes a value of type error_code, mb denotes a value satisfying mutable buffer sequence requirements, rh denotes a value meeting ReadHandler requirements, cb denotes a value satisfying constant buffer sequence requirements, and wh denotes a value meeting WriteHandler requirements.

Table 7.32. StreamHandleService requirements

expression

return type

assertion/note
pre/post-condition

a.read_some(b, mb, ec);

size_t

pre: a.is_open(b).

Reads one or more bytes of data from a handle b.

The mutable buffer sequence mb specifies memory where the data should be placed. The operation shall always fill a buffer in the sequence completely before proceeding to the next.

If successful, returns the number of bytes read. Otherwise returns 0. If the total size of all buffers in the sequence mb is 0, the function shall return 0 immediately.

If the operation completes due to graceful connection closure by the peer, the operation shall fail with error::eof.

a.async_read_some(b, mb, rh);

void

pre: a.is_open(b).

Initiates an asynchronous operation to read one or more bytes of data from a handle b. The operation is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

The mutable buffer sequence mb specifies memory where the data should be placed. The operation shall always fill a buffer in the sequence completely before proceeding to the next.

The implementation shall maintain one or more copies of mb until such time as the read operation no longer requires access to the memory specified by the buffers in the sequence. The program must ensure the memory is valid until:

— the last copy of mb is destroyed, or

— the handler for the asynchronous operation is invoked,

whichever comes first. If the total size of all buffers in the sequence mb is 0, the asynchronous read operation shall complete immediately and pass 0 as the argument to the handler that specifies the number of bytes read.

If the operation completes due to graceful connection closure by the peer, the operation shall fail with error::eof.

If the operation completes successfully, the ReadHandler object rh is invoked with the number of bytes transferred. Otherwise it is invoked with 0.

a.write_some(b, cb, ec);

size_t

pre: a.is_open(b).

Writes one or more bytes of data to a handle b.

The constant buffer sequence cb specifies memory where the data to be written is located. The operation shall always write a buffer in the sequence completely before proceeding to the next.

If successful, returns the number of bytes written. Otherwise returns 0. If the total size of all buffers in the sequence cb is 0, the function shall return 0 immediately.

a.async_write_some(b, cb, wh);

void

pre: a.is_open(b).

Initiates an asynchronous operation to write one or more bytes of data to a handle b. The operation is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

The constant buffer sequence cb specifies memory where the data to be written is located. The operation shall always write a buffer in the sequence completely before proceeding to the next.

The implementation shall maintain one or more copies of cb until such time as the write operation no longer requires access to the memory specified by the buffers in the sequence. The program must ensure the memory is valid until:

— the last copy of cb is destroyed, or

— the handler for the asynchronous operation is invoked,

whichever comes first. If the total size of all buffers in the sequence cb is 0, the asynchronous operation shall complete immediately and pass 0 as the argument to the handler that specifies the number of bytes read.

If the operation completes successfully, the WriteHandler object wh is invoked with the number of bytes transferred. Otherwise it is invoked with 0.


A stream socket service must meet the requirements for a socket service, as well as the additional requirements listed below.

In the table below, X denotes a stream socket service class, a denotes a value of type X, b denotes a value of type X::implementation_type, ec denotes a value of type error_code, f denotes a value of type socket_base::message_flags, mb denotes a value satisfying mutable buffer sequence requirements, rh denotes a value meeting ReadHandler requirements, cb denotes a value satisfying constant buffer sequence requirements, and wh denotes a value meeting WriteHandler requirements.

Table 7.33. StreamSocketService requirements

expression

return type

assertion/note
pre/post-condition

a.receive(b, mb, f, ec);

size_t

pre: a.is_open(b).

Reads one or more bytes of data from a connected socket b.

The mutable buffer sequence mb specifies memory where the data should be placed. The operation shall always fill a buffer in the sequence completely before proceeding to the next.

If successful, returns the number of bytes read. Otherwise returns 0. If the total size of all buffers in the sequence mb is 0, the function shall return 0 immediately.

If the operation completes due to graceful connection closure by the peer, the operation shall fail with error::eof.

a.async_receive(b, mb, f, rh);

void

pre: a.is_open(b).

Initiates an asynchronous operation to read one or more bytes of data from a connected socket b. The operation is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

The mutable buffer sequence mb specifies memory where the data should be placed. The operation shall always fill a buffer in the sequence completely before proceeding to the next.

The implementation shall maintain one or more copies of mb until such time as the read operation no longer requires access to the memory specified by the buffers in the sequence. The program must ensure the memory is valid until:

— the last copy of mb is destroyed, or

— the handler for the asynchronous operation is invoked,

whichever comes first. If the total size of all buffers in the sequence mb is 0, the asynchronous read operation shall complete immediately and pass 0 as the argument to the handler that specifies the number of bytes read.

If the operation completes due to graceful connection closure by the peer, the operation shall fail with error::eof.

If the operation completes successfully, the ReadHandler object rh is invoked with the number of bytes transferred. Otherwise it is invoked with 0.

a.send(b, cb, f, ec);

size_t

pre: a.is_open(b).

Writes one or more bytes of data to a connected socket b.

The constant buffer sequence cb specifies memory where the data to be written is located. The operation shall always write a buffer in the sequence completely before proceeding to the next.

If successful, returns the number of bytes written. Otherwise returns 0. If the total size of all buffers in the sequence cb is 0, the function shall return 0 immediately.

a.async_send(b, cb, f, wh);

void

pre: a.is_open(b).

Initiates an asynchronous operation to write one or more bytes of data to a connected socket b. The operation is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

The constant buffer sequence cb specifies memory where the data to be written is located. The operation shall always write a buffer in the sequence completely before proceeding to the next.

The implementation shall maintain one or more copies of cb until such time as the write operation no longer requires access to the memory specified by the buffers in the sequence. The program must ensure the memory is valid until:

— the last copy of cb is destroyed, or

— the handler for the asynchronous operation is invoked,

whichever comes first. If the total size of all buffers in the sequence cb is 0, the asynchronous operation shall complete immediately and pass 0 as the argument to the handler that specifies the number of bytes read.

If the operation completes successfully, the WriteHandler object wh is invoked with the number of bytes transferred. Otherwise it is invoked with 0.


In the table below, a denotes a synchronous random-access read device object, o denotes an offset of type boost::uint64_t, mb denotes an object satisfying mutable buffer sequence requirements, and ec denotes an object of type error_code.

Table 7.34. Buffer-oriented synchronous random-access read device requirements

operation

type

semantics, pre/post-conditions

a.read_some_at(o, mb);

size_t

Equivalent to:

error_code ec;
size_t s = a.read_some_at(o, mb, ec);
if (ec) throw system_error(ec);
return s;

a.read_some_at(o, mb, ec);

size_t

Reads one or more bytes of data from the device a at offset o.

The mutable buffer sequence mb specifies memory where the data should be placed. The read_some_at operation shall always fill a buffer in the sequence completely before proceeding to the next.

If successful, returns the number of bytes read and sets ec such that !ec is true. If an error occurred, returns 0 and sets ec such that !!ec is true.

If the total size of all buffers in the sequence mb is 0, the function shall return 0 immediately.


In the table below, a denotes a synchronous random-access write device object, o denotes an offset of type boost::uint64_t, cb denotes an object satisfying constant buffer sequence requirements, and ec denotes an object of type error_code.

Table 7.35. Buffer-oriented synchronous random-access write device requirements

operation

type

semantics, pre/post-conditions

a.write_some_at(o, cb);

size_t

Equivalent to:

error_code ec;
size_t s = a.write_some(o, cb, ec);
if (ec) throw system_error(ec);
return s;

a.write_some_at(o, cb, ec);

size_t

Writes one or more bytes of data to the device a at offset o.

The constant buffer sequence cb specifies memory where the data to be written is located. The write_some_at operation shall always write a buffer in the sequence completely before proceeding to the next.

If successful, returns the number of bytes written and sets ec such that !ec is true. If an error occurred, returns 0 and sets ec such that !!ec is true.

If the total size of all buffers in the sequence cb is 0, the function shall return 0 immediately.


In the table below, a denotes a synchronous read stream object, mb denotes an object satisfying mutable buffer sequence requirements, and ec denotes an object of type error_code.

Table 7.36. Buffer-oriented synchronous read stream requirements

operation

type

semantics, pre/post-conditions

a.read_some(mb);

size_t

Equivalent to:

error_code ec;
size_t s = a.read_some(mb, ec);
if (ec) throw system_error(ec);
return s;

a.read_some(mb, ec);

size_t

Reads one or more bytes of data from the stream a.

The mutable buffer sequence mb specifies memory where the data should be placed. The read_some operation shall always fill a buffer in the sequence completely before proceeding to the next.

If successful, returns the number of bytes read and sets ec such that !ec is true. If an error occurred, returns 0 and sets ec such that !!ec is true.

If the total size of all buffers in the sequence mb is 0, the function shall return 0 immediately.


In the table below, a denotes a synchronous write stream object, cb denotes an object satisfying constant buffer sequence requirements, and ec denotes an object of type error_code.

Table 7.37. Buffer-oriented synchronous write stream requirements

operation

type

semantics, pre/post-conditions

a.write_some(cb);

size_t

Equivalent to:

error_code ec;
size_t s = a.write_some(cb, ec);
if (ec) throw system_error(ec);
return s;

a.write_some(cb, ec);

size_t

Writes one or more bytes of data to the stream a.

The constant buffer sequence cb specifies memory where the data to be written is located. The write_some operation shall always write a buffer in the sequence completely before proceeding to the next.

If successful, returns the number of bytes written and sets ec such that !ec is true. If an error occurred, returns 0 and sets ec such that !!ec is true.

If the total size of all buffers in the sequence cb is 0, the function shall return 0 immediately.


In the table below, X denotes a time traits class for time type Time, t, t1, and t2 denote values of type Time, and d denotes a value of type X::duration_type.

Table 7.38. TimeTraits requirements

expression

return type

assertion/note
pre/post-condition

X::time_type

Time

Represents an absolute time. Must support default construction, and meet the requirements for CopyConstructible and Assignable.

X::duration_type

Represents the difference between two absolute times. Must support default construction, and meet the requirements for CopyConstructible and Assignable. A duration can be positive, negative, or zero.

X::now();

time_type

Returns the current time.

X::add(t, d);

time_type

Returns a new absolute time resulting from adding the duration d to the absolute time t.

X::subtract(t1, t2);

duration_type

Returns the duration resulting from subtracting t2 from t1.

X::less_than(t1, t2);

bool

Returns whether t1 is to be treated as less than t2.

X::to_posix_duration(d);

date_time::time_duration_type

Returns the date_time::time_duration_type value that most closely represents the duration d.


A timer service must meet the requirements for an I/O object service, as well as the additional requirements listed below.

In the table below, X denotes a timer service class for time type Time and traits type TimeTraits, a denotes a value of type X, b denotes a value of type X::implementation_type, t denotes a value of type Time, d denotes a value of type TimeTraits::duration_type, e denotes a value of type error_code, and h denotes a value meeting WaitHandler requirements.

Table 7.39. TimerService requirements

expression

return type

assertion/note
pre/post-condition

a.destroy(b);

From IoObjectService requirements. Implicitly cancels asynchronous wait operations, as if by calling a.cancel(b, e).

a.cancel(b, e);

size_t

Causes any outstanding asynchronous wait operations to complete as soon as possible. Handlers for cancelled operations shall be passed the error code error::operation_aborted. Sets e to indicate success or failure. Returns the number of operations that were cancelled.

a.expires_at(b);

Time

a.expires_at(b, t, e);

size_t

Implicitly cancels asynchronous wait operations, as if by calling a.cancel(b, e). Returns the number of operations that were cancelled.
post: a.expires_at(b) == t.

a.expires_from_now(b);

TimeTraits::duration_type

Returns a value equivalent to TimeTraits::subtract(a.expires_at(b), TimeTraits::now()).

a.expires_from_now(b, d, e);

size_t

Equivalent to a.expires_at(b, TimeTraits::add(TimeTraits::now(), d), e).

a.wait(b, e);

error_code

Sets e to indicate success or failure. Returns e.
post: !!e || !TimeTraits::lt(TimeTraits::now(), a.expires_at(b)).

a.async_wait(b, h);

Initiates an asynchronous wait operation that is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

The handler shall be posted for execution only if the condition !!ec || !TimeTraits::lt(TimeTraits::now(), a.expires_at(b)) holds, where ec is the error code to be passed to the handler.


A waitable timer service must meet the requirements for an I/O object service, as well as the additional requirements listed below.

In the table below, X denotes a waitable timer service class for clock type Clock, where Clock meets the C++11 clock type requirements, a denotes a value of type X, b denotes a value of type X::implementation_type, t denotes a value of type Clock::time_point, d denotes a value of type Clock::duration, e denotes a value of type error_code, and h denotes a value meeting WaitHandler requirements.

Table 7.40. WaitableTimerService requirements

expression

return type

assertion/note
pre/post-condition

a.destroy(b);

From IoObjectService requirements. Implicitly cancels asynchronous wait operations, as if by calling a.cancel(b, e).

a.cancel(b, e);

size_t

Causes any outstanding asynchronous wait operations to complete as soon as possible. Handlers for cancelled operations shall be passed the error code error::operation_aborted. Sets e to indicate success or failure. Returns the number of operations that were cancelled.

a.expires_at(b);

Clock::time_point

a.expires_at(b, t, e);

size_t

Implicitly cancels asynchronous wait operations, as if by calling a.cancel(b, e). Returns the number of operations that were cancelled.
post: a.expires_at(b) == t.

a.expires_from_now(b);

Clock::duration

Returns a value equivalent to a.expires_at(b) - Clock::now().

a.expires_from_now(b, d, e);

size_t

Equivalent to a.expires_at(b, Clock::now() + d, e).

a.wait(b, e);

error_code

Sets e to indicate success or failure. Returns e.
post: !!e || !(Clock::now() < a.expires_at(b)).

a.async_wait(b, h);

Initiates an asynchronous wait operation that is performed via the io_service object a.get_io_service() and behaves according to asynchronous operation requirements.

The handler shall be posted for execution only if the condition !!ec || !(Clock::now() < a.expires_at(b)) holds, where ec is the error code to be passed to the handler.


A wait handler must meet the requirements for a handler. A value h of a wait handler class should work correctly in the expression h(ec), where ec is an lvalue of type const error_code.

Examples

A free function as a wait handler:

void wait_handler(
    const boost::system::error_code& ec)
{
  ...
}

A wait handler function object:

struct wait_handler
{
  ...
  void operator()(
      const boost::system::error_code& ec)
  {
    ...
  }
  ...
};

A non-static class member function adapted to a wait handler using bind():

void my_class::wait_handler(
    const boost::system::error_code& ec)
{
  ...
}
...
socket.async_wait(...,
    boost::bind(&my_class::wait_handler,
      this, boost::asio::placeholders::error));

In the table below, X denotes a wait traits class for clock type Clock, where Clock meets the C++11 type requirements for a clock, and d denotes a value of type Clock::duration.

Table 7.41. WaitTraits requirements

expression

return type

assertion/note
pre/post-condition

X::to_wait_duration(d);

Clock::duration

Returns the maximum duration to be used for an individual, implementation-defined wait operation.


A write handler must meet the requirements for a handler. A value h of a write handler class should work correctly in the expression h(ec, s), where ec is an lvalue of type const error_code and s is an lvalue of type const size_t.

Examples

A free function as a write handler:

void write_handler(
    const boost::system::error_code& ec,
    std::size_t bytes_transferred)
{
  ...
}

A write handler function object:

struct write_handler
{
  ...
  void operator()(
      const boost::system::error_code& ec,
      std::size_t bytes_transferred)
  {
    ...
  }
  ...
};

A non-static class member function adapted to a write handler using bind():

void my_class::write_handler(
    const boost::system::error_code& ec,
    std::size_t bytes_transferred)
{
  ...
}
...
socket.async_write(...,
    boost::bind(&my_class::write_handler,
      this, boost::asio::placeholders::error,
      boost::asio::placeholders::bytes_transferred));

template<
    typename Service>
void add_service(
    io_service & ios,
    Service * svc);

This function is used to add a service to the io_service.

Parameters

ios

The io_service object that owns the service.

svc

The service object. On success, ownership of the service object is transferred to the io_service. When the io_service object is destroyed, it will destroy the service object by performing:

delete static_cast<io_service::service*>(svc)

Exceptions

boost::asio::service_already_exists

Thrown if a service of the given type is already present in the io_service.

boost::asio::invalid_service_owner

Thrown if the service's owning io_service is not the io_service object specified by the ios parameter.

Requirements

Header: boost/asio/io_service.hpp

Convenience header: boost/asio.hpp

Default allocation function for handlers.

void * asio_handler_allocate(
    std::size_t size,
    ... );

Asynchronous operations may need to allocate temporary objects. Since asynchronous operations have a handler function object, these temporary objects can be said to be associated with the handler.

Implement asio_handler_allocate and asio_handler_deallocate for your own handlers to provide custom allocation for these temporary objects.

The default implementation of these allocation hooks uses operator new and operator delete.

Remarks

All temporary objects associated with a handler will be deallocated before the upcall to the handler is performed. This allows the same memory to be reused for a subsequent asynchronous operation initiated by the handler.

Example
class my_handler;

void* asio_handler_allocate(std::size_t size, my_handler* context)
{
  return ::operator new(size);
}

void asio_handler_deallocate(void* pointer, std::size_t size,
    my_handler* context)
{
  ::operator delete(pointer);
}
Requirements

Header: boost/asio/handler_alloc_hook.hpp

Convenience header: boost/asio.hpp

Default deallocation function for handlers.

void asio_handler_deallocate(
    void * pointer,
    std::size_t size,
    ... );

Implement asio_handler_allocate and asio_handler_deallocate for your own handlers to provide custom allocation for the associated temporary objects.

The default implementation of these allocation hooks uses operator new and operator delete.

Requirements

Header: boost/asio/handler_alloc_hook.hpp

Convenience header: boost/asio.hpp

Default invoke function for handlers.

template<
    typename Function>
void asio_handler_invoke(
    Function & function,
    ... );
  » more...

template<
    typename Function>
void asio_handler_invoke(
    const Function & function,
    ... );
  » more...

Completion handlers for asynchronous operations are invoked by the io_service associated with the corresponding object (e.g. a socket or deadline_timer). Certain guarantees are made on when the handler may be invoked, in particular that a handler can only be invoked from a thread that is currently calling run() on the corresponding io_service object. Handlers may subsequently be invoked through other objects (such as io_service::strand objects) that provide additional guarantees.

When asynchronous operations are composed from other asynchronous operations, all intermediate handlers should be invoked using the same method as the final handler. This is required to ensure that user-defined objects are not accessed in a way that may violate the guarantees. This hooking function ensures that the invoked method used for the final handler is accessible at each intermediate step.

Implement asio_handler_invoke for your own handlers to specify a custom invocation strategy.

This default implementation invokes the function object like so:

function();

If necessary, the default implementation makes a copy of the function object so that the non-const operator() can be used.

Example
class my_handler;

template <typename Function>
void asio_handler_invoke(Function function, my_handler* context)
{
  context->strand_.dispatch(function);
}
Requirements

Header: boost/asio/handler_invoke_hook.hpp

Convenience header: boost/asio.hpp

Default handler invocation hook used for non-const function objects.

template<
    typename Function>
void asio_handler_invoke(
    Function & function,
    ... );

Default handler invocation hook used for const function objects.

template<
    typename Function>
void asio_handler_invoke(
    const Function & function,
    ... );

Default continuation function for handlers.

bool asio_handler_is_continuation(
    ... );

Asynchronous operations may represent a continuation of the asynchronous control flow associated with the current handler. The implementation can use this knowledge to optimise scheduling of the handler.

Implement asio_handler_is_continuation for your own handlers to indicate when a handler represents a continuation.

The default implementation of the continuation hook returns false.

Example
class my_handler;

bool asio_handler_is_continuation(my_handler* context)
{
  return true;
}
Requirements

Header: boost/asio/handler_continuation_hook.hpp

Convenience header: boost/asio.hpp

Asynchronously establishes a socket connection by trying each endpoint in a sequence.

template<
    typename Protocol,
    typename SocketService,
    typename Iterator,
    typename ComposedConnectHandler>
void-or-deduced async_connect(
    basic_socket< Protocol, SocketService > & s,
    Iterator begin,
    ComposedConnectHandler handler);
  » more...

template<
    typename Protocol,
    typename SocketService,
    typename Iterator,
    typename ComposedConnectHandler>
void-or-deduced async_connect(
    basic_socket< Protocol, SocketService > & s,
    Iterator begin,
    Iterator end,
    ComposedConnectHandler handler);
  » more...

template<
    typename Protocol,
    typename SocketService,
    typename Iterator,
    typename ConnectCondition,
    typename ComposedConnectHandler>
void-or-deduced async_connect(
    basic_socket< Protocol, SocketService > & s,
    Iterator begin,
    ConnectCondition connect_condition,
    ComposedConnectHandler handler);
  » more...

template<
    typename Protocol,
    typename SocketService,
    typename Iterator,
    typename ConnectCondition,
    typename ComposedConnectHandler>
void-or-deduced async_connect(
    basic_socket< Protocol, SocketService > & s,
    Iterator begin,
    Iterator end,
    ConnectCondition connect_condition,
    ComposedConnectHandler handler);
  » more...
Requirements

Header: boost/asio/connect.hpp

Convenience header: boost/asio.hpp

Asynchronously establishes a socket connection by trying each endpoint in a sequence.

template<
    typename Protocol,
    typename SocketService,
    typename Iterator,
    typename ComposedConnectHandler>
void-or-deduced async_connect(
    basic_socket< Protocol, SocketService > & s,
    Iterator begin,
    ComposedConnectHandler handler);

This function attempts to connect a socket to one of a sequence of endpoints. It does this by repeated calls to the socket's async_connect member function, once for each endpoint in the sequence, until a connection is successfully established.

Parameters

s

The socket to be connected. If the socket is already open, it will be closed.

begin

An iterator pointing to the start of a sequence of endpoints.

handler

The handler to be called when the connect operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  // Result of operation. if the sequence is empty, set to
  // boost::asio::error::not_found. Otherwise, contains the
  // error from the last connection attempt.
  const boost::system::error_code& error,

  // On success, an iterator denoting the successfully
  // connected endpoint. Otherwise, the end iterator.
  Iterator iterator
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

This overload assumes that a default constructed object of type Iterator represents the end of the sequence. This is a valid assumption for iterator types such as boost::asio::ip::tcp::resolver::iterator.

Example
tcp::resolver r(io_service);
tcp::resolver::query q("host", "service");
tcp::socket s(io_service);

// ...

r.async_resolve(q, resolve_handler);

// ...

void resolve_handler(
    const boost::system::error_code& ec,
    tcp::resolver::iterator i)
{
  if (!ec)
  {
    boost::asio::async_connect(s, i, connect_handler);
  }
}

// ...

void connect_handler(
    const boost::system::error_code& ec,
    tcp::resolver::iterator i)
{
  // ...
}

Asynchronously establishes a socket connection by trying each endpoint in a sequence.

template<
    typename Protocol,
    typename SocketService,
    typename Iterator,
    typename ComposedConnectHandler>
void-or-deduced async_connect(
    basic_socket< Protocol, SocketService > & s,
    Iterator begin,
    Iterator end,
    ComposedConnectHandler handler);

This function attempts to connect a socket to one of a sequence of endpoints. It does this by repeated calls to the socket's async_connect member function, once for each endpoint in the sequence, until a connection is successfully established.

Parameters

s

The socket to be connected. If the socket is already open, it will be closed.

begin

An iterator pointing to the start of a sequence of endpoints.

end

An iterator pointing to the end of a sequence of endpoints.

handler

The handler to be called when the connect operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  // Result of operation. if the sequence is empty, set to
  // boost::asio::error::not_found. Otherwise, contains the
  // error from the last connection attempt.
  const boost::system::error_code& error,

  // On success, an iterator denoting the successfully
  // connected endpoint. Otherwise, the end iterator.
  Iterator iterator
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Example
tcp::resolver r(io_service);
tcp::resolver::query q("host", "service");
tcp::socket s(io_service);

// ...

r.async_resolve(q, resolve_handler);

// ...

void resolve_handler(
    const boost::system::error_code& ec,
    tcp::resolver::iterator i)
{
  if (!ec)
  {
    tcp::resolver::iterator end;
    boost::asio::async_connect(s, i, end, connect_handler);
  }
}

// ...

void connect_handler(
    const boost::system::error_code& ec,
    tcp::resolver::iterator i)
{
  // ...
}

Asynchronously establishes a socket connection by trying each endpoint in a sequence.

template<
    typename Protocol,
    typename SocketService,
    typename Iterator,
    typename ConnectCondition,
    typename ComposedConnectHandler>
void-or-deduced async_connect(
    basic_socket< Protocol, SocketService > & s,
    Iterator begin,
    ConnectCondition connect_condition,
    ComposedConnectHandler handler);

This function attempts to connect a socket to one of a sequence of endpoints. It does this by repeated calls to the socket's async_connect member function, once for each endpoint in the sequence, until a connection is successfully established.

Parameters

s

The socket to be connected. If the socket is already open, it will be closed.

begin

An iterator pointing to the start of a sequence of endpoints.

connect_condition

A function object that is called prior to each connection attempt. The signature of the function object must be:

Iterator connect_condition(
    const boost::system::error_code& ec,
    Iterator next);

The ec parameter contains the result from the most recent connect operation. Before the first connection attempt, ec is always set to indicate success. The next parameter is an iterator pointing to the next endpoint to be tried. The function object should return the next iterator, but is permitted to return a different iterator so that endpoints may be skipped. The implementation guarantees that the function object will never be called with the end iterator.

handler

The handler to be called when the connect operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  // Result of operation. if the sequence is empty, set to
  // boost::asio::error::not_found. Otherwise, contains the
  // error from the last connection attempt.
  const boost::system::error_code& error,

  // On success, an iterator denoting the successfully
  // connected endpoint. Otherwise, the end iterator.
  Iterator iterator
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

This overload assumes that a default constructed object of type Iterator represents the end of the sequence. This is a valid assumption for iterator types such as boost::asio::ip::tcp::resolver::iterator.

Example

The following connect condition function object can be used to output information about the individual connection attempts:

struct my_connect_condition
{
  template <typename Iterator>
  Iterator operator()(
      const boost::system::error_code& ec,
      Iterator next)
  {
    if (ec) std::cout << "Error: " << ec.message() << std::endl;
    std::cout << "Trying: " << next->endpoint() << std::endl;
    return next;
  }
};

It would be used with the boost::asio::connect function as follows:

tcp::resolver r(io_service);
tcp::resolver::query q("host", "service");
tcp::socket s(io_service);

// ...

r.async_resolve(q, resolve_handler);

// ...

void resolve_handler(
    const boost::system::error_code& ec,
    tcp::resolver::iterator i)
{
  if (!ec)
  {
    boost::asio::async_connect(s, i,
        my_connect_condition(),
        connect_handler);
  }
}

// ...

void connect_handler(
    const boost::system::error_code& ec,
    tcp::resolver::iterator i)
{
  if (ec)
  {
    // An error occurred.
  }
  else
  {
    std::cout << "Connected to: " << i->endpoint() << std::endl;
  }
}

Asynchronously establishes a socket connection by trying each endpoint in a sequence.

template<
    typename Protocol,
    typename SocketService,
    typename Iterator,
    typename ConnectCondition,
    typename ComposedConnectHandler>
void-or-deduced async_connect(
    basic_socket< Protocol, SocketService > & s,
    Iterator begin,
    Iterator end,
    ConnectCondition connect_condition,
    ComposedConnectHandler handler);

This function attempts to connect a socket to one of a sequence of endpoints. It does this by repeated calls to the socket's async_connect member function, once for each endpoint in the sequence, until a connection is successfully established.

Parameters

s

The socket to be connected. If the socket is already open, it will be closed.

begin

An iterator pointing to the start of a sequence of endpoints.

end

An iterator pointing to the end of a sequence of endpoints.

connect_condition

A function object that is called prior to each connection attempt. The signature of the function object must be:

Iterator connect_condition(
    const boost::system::error_code& ec,
    Iterator next);

The ec parameter contains the result from the most recent connect operation. Before the first connection attempt, ec is always set to indicate success. The next parameter is an iterator pointing to the next endpoint to be tried. The function object should return the next iterator, but is permitted to return a different iterator so that endpoints may be skipped. The implementation guarantees that the function object will never be called with the end iterator.

handler

The handler to be called when the connect operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  // Result of operation. if the sequence is empty, set to
  // boost::asio::error::not_found. Otherwise, contains the
  // error from the last connection attempt.
  const boost::system::error_code& error,

  // On success, an iterator denoting the successfully
  // connected endpoint. Otherwise, the end iterator.
  Iterator iterator
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Example

The following connect condition function object can be used to output information about the individual connection attempts:

struct my_connect_condition
{
  template <typename Iterator>
  Iterator operator()(
      const boost::system::error_code& ec,
      Iterator next)
  {
    if (ec) std::cout << "Error: " << ec.message() << std::endl;
    std::cout << "Trying: " << next->endpoint() << std::endl;
    return next;
  }
};

It would be used with the boost::asio::connect function as follows:

tcp::resolver r(io_service);
tcp::resolver::query q("host", "service");
tcp::socket s(io_service);

// ...

r.async_resolve(q, resolve_handler);

// ...

void resolve_handler(
    const boost::system::error_code& ec,
    tcp::resolver::iterator i)
{
  if (!ec)
  {
    tcp::resolver::iterator end;
    boost::asio::async_connect(s, i, end,
        my_connect_condition(),
        connect_handler);
  }
}

// ...

void connect_handler(
    const boost::system::error_code& ec,
    tcp::resolver::iterator i)
{
  if (ec)
  {
    // An error occurred.
  }
  else
  {
    std::cout << "Connected to: " << i->endpoint() << std::endl;
  }
}

Start an asynchronous operation to read a certain amount of data from a stream.

template<
    typename AsyncReadStream,
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_read(
    AsyncReadStream & s,
    const MutableBufferSequence & buffers,
    ReadHandler handler);
  » more...

template<
    typename AsyncReadStream,
    typename MutableBufferSequence,
    typename CompletionCondition,
    typename ReadHandler>
void-or-deduced async_read(
    AsyncReadStream & s,
    const MutableBufferSequence & buffers,
    CompletionCondition completion_condition,
    ReadHandler handler);
  » more...

template<
    typename AsyncReadStream,
    typename Allocator,
    typename ReadHandler>
void-or-deduced async_read(
    AsyncReadStream & s,
    basic_streambuf< Allocator > & b,
    ReadHandler handler);
  » more...

template<
    typename AsyncReadStream,
    typename Allocator,
    typename CompletionCondition,
    typename ReadHandler>
void-or-deduced async_read(
    AsyncReadStream & s,
    basic_streambuf< Allocator > & b,
    CompletionCondition completion_condition,
    ReadHandler handler);
  » more...
Requirements

Header: boost/asio/read.hpp

Convenience header: boost/asio.hpp

Start an asynchronous operation to read a certain amount of data from a stream.

template<
    typename AsyncReadStream,
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_read(
    AsyncReadStream & s,
    const MutableBufferSequence & buffers,
    ReadHandler handler);

This function is used to asynchronously read a certain number of bytes of data from a stream. The function call always returns immediately. The asynchronous operation will continue until one of the following conditions is true:

  • The supplied buffers are full. That is, the bytes transferred is equal to the sum of the buffer sizes.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the stream's async_read_some function, and is known as a composed operation. The program must ensure that the stream performs no other read operations (such as async_read, the stream's async_read_some function, or any other composed operations that perform reads) until this operation completes.

Parameters

s

The stream from which the data is to be read. The type must support the AsyncReadStream concept.

buffers

One or more buffers into which the data will be read. The sum of the buffer sizes indicates the maximum number of bytes to read from the stream. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

handler

The handler to be called when the read operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.

  std::size_t bytes_transferred           // Number of bytes copied into the
                                          // buffers. If an error occurred,
                                          // this will be the  number of
                                          // bytes successfully transferred
                                          // prior to the error.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Example

To read into a single data buffer use the buffer function as follows:

boost::asio::async_read(s, boost::asio::buffer(data, size), handler);

See the buffer documentation for information on reading into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Remarks

This overload is equivalent to calling:

boost::asio::async_read(
    s, buffers,
    boost::asio::transfer_all(),
    handler);

Start an asynchronous operation to read a certain amount of data from a stream.

template<
    typename AsyncReadStream,
    typename MutableBufferSequence,
    typename CompletionCondition,
    typename ReadHandler>
void-or-deduced async_read(
    AsyncReadStream & s,
    const MutableBufferSequence & buffers,
    CompletionCondition completion_condition,
    ReadHandler handler);

This function is used to asynchronously read a certain number of bytes of data from a stream. The function call always returns immediately. The asynchronous operation will continue until one of the following conditions is true:

  • The supplied buffers are full. That is, the bytes transferred is equal to the sum of the buffer sizes.
  • The completion_condition function object returns 0.
Parameters

s

The stream from which the data is to be read. The type must support the AsyncReadStream concept.

buffers

One or more buffers into which the data will be read. The sum of the buffer sizes indicates the maximum number of bytes to read from the stream. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

completion_condition

The function object to be called to determine whether the read operation is complete. The signature of the function object must be:

std::size_t completion_condition(
  // Result of latest async_read_some operation.
  const boost::system::error_code& error,

  // Number of bytes transferred so far.
  std::size_t bytes_transferred
);

A return value of 0 indicates that the read operation is complete. A non-zero return value indicates the maximum number of bytes to be read on the next call to the stream's async_read_some function.

handler

The handler to be called when the read operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.

  std::size_t bytes_transferred           // Number of bytes copied into the
                                          // buffers. If an error occurred,
                                          // this will be the  number of
                                          // bytes successfully transferred
                                          // prior to the error.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Example

To read into a single data buffer use the buffer function as follows:

boost::asio::async_read(s,
    boost::asio::buffer(data, size),
    boost::asio::transfer_at_least(32),
    handler);

See the buffer documentation for information on reading into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Start an asynchronous operation to read a certain amount of data from a stream.

template<
    typename AsyncReadStream,
    typename Allocator,
    typename ReadHandler>
void-or-deduced async_read(
    AsyncReadStream & s,
    basic_streambuf< Allocator > & b,
    ReadHandler handler);

This function is used to asynchronously read a certain number of bytes of data from a stream. The function call always returns immediately. The asynchronous operation will continue until one of the following conditions is true:

  • The supplied buffer is full (that is, it has reached maximum size).
  • An error occurred.

This operation is implemented in terms of zero or more calls to the stream's async_read_some function, and is known as a composed operation. The program must ensure that the stream performs no other read operations (such as async_read, the stream's async_read_some function, or any other composed operations that perform reads) until this operation completes.

Parameters

s

The stream from which the data is to be read. The type must support the AsyncReadStream concept.

b

A basic_streambuf object into which the data will be read. Ownership of the streambuf is retained by the caller, which must guarantee that it remains valid until the handler is called.

handler

The handler to be called when the read operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.

  std::size_t bytes_transferred           // Number of bytes copied into the
                                          // buffers. If an error occurred,
                                          // this will be the  number of
                                          // bytes successfully transferred
                                          // prior to the error.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

This overload is equivalent to calling:

boost::asio::async_read(
    s, b,
    boost::asio::transfer_all(),
    handler);

Start an asynchronous operation to read a certain amount of data from a stream.

template<
    typename AsyncReadStream,
    typename Allocator,
    typename CompletionCondition,
    typename ReadHandler>
void-or-deduced async_read(
    AsyncReadStream & s,
    basic_streambuf< Allocator > & b,
    CompletionCondition completion_condition,
    ReadHandler handler);

This function is used to asynchronously read a certain number of bytes of data from a stream. The function call always returns immediately. The asynchronous operation will continue until one of the following conditions is true:

  • The supplied buffer is full (that is, it has reached maximum size).
  • The completion_condition function object returns 0.

This operation is implemented in terms of zero or more calls to the stream's async_read_some function, and is known as a composed operation. The program must ensure that the stream performs no other read operations (such as async_read, the stream's async_read_some function, or any other composed operations that perform reads) until this operation completes.

Parameters

s

The stream from which the data is to be read. The type must support the AsyncReadStream concept.

b

A basic_streambuf object into which the data will be read. Ownership of the streambuf is retained by the caller, which must guarantee that it remains valid until the handler is called.

completion_condition

The function object to be called to determine whether the read operation is complete. The signature of the function object must be:

std::size_t completion_condition(
  // Result of latest async_read_some operation.
  const boost::system::error_code& error,

  // Number of bytes transferred so far.
  std::size_t bytes_transferred
);

A return value of 0 indicates that the read operation is complete. A non-zero return value indicates the maximum number of bytes to be read on the next call to the stream's async_read_some function.

handler

The handler to be called when the read operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.

  std::size_t bytes_transferred           // Number of bytes copied into the
                                          // buffers. If an error occurred,
                                          // this will be the  number of
                                          // bytes successfully transferred
                                          // prior to the error.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Start an asynchronous operation to read a certain amount of data at the specified offset.

template<
    typename AsyncRandomAccessReadDevice,
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_read_at(
    AsyncRandomAccessReadDevice & d,
    uint64_t offset,
    const MutableBufferSequence & buffers,
    ReadHandler handler);
  » more...

template<
    typename AsyncRandomAccessReadDevice,
    typename MutableBufferSequence,
    typename CompletionCondition,
    typename ReadHandler>
void-or-deduced async_read_at(
    AsyncRandomAccessReadDevice & d,
    uint64_t offset,
    const MutableBufferSequence & buffers,
    CompletionCondition completion_condition,
    ReadHandler handler);
  » more...

template<
    typename AsyncRandomAccessReadDevice,
    typename Allocator,
    typename ReadHandler>
void-or-deduced async_read_at(
    AsyncRandomAccessReadDevice & d,
    uint64_t offset,
    basic_streambuf< Allocator > & b,
    ReadHandler handler);
  » more...

template<
    typename AsyncRandomAccessReadDevice,
    typename Allocator,
    typename CompletionCondition,
    typename ReadHandler>
void-or-deduced async_read_at(
    AsyncRandomAccessReadDevice & d,
    uint64_t offset,
    basic_streambuf< Allocator > & b,
    CompletionCondition completion_condition,
    ReadHandler handler);
  » more...
Requirements

Header: boost/asio/read_at.hpp

Convenience header: boost/asio.hpp

Start an asynchronous operation to read a certain amount of data at the specified offset.

template<
    typename AsyncRandomAccessReadDevice,
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_read_at(
    AsyncRandomAccessReadDevice & d,
    uint64_t offset,
    const MutableBufferSequence & buffers,
    ReadHandler handler);

This function is used to asynchronously read a certain number of bytes of data from a random access device at the specified offset. The function call always returns immediately. The asynchronous operation will continue until one of the following conditions is true:

  • The supplied buffers are full. That is, the bytes transferred is equal to the sum of the buffer sizes.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the device's async_read_some_at function.

Parameters

d

The device from which the data is to be read. The type must support the AsyncRandomAccessReadDevice concept.

offset

The offset at which the data will be read.

buffers

One or more buffers into which the data will be read. The sum of the buffer sizes indicates the maximum number of bytes to read from the device. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

handler

The handler to be called when the read operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  // Result of operation.
  const boost::system::error_code& error,

  // Number of bytes copied into the buffers. If an error
  // occurred, this will be the number of bytes successfully
  // transferred prior to the error.
  std::size_t bytes_transferred
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Example

To read into a single data buffer use the buffer function as follows:

boost::asio::async_read_at(d, 42, boost::asio::buffer(data, size), handler);

See the buffer documentation for information on reading into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Remarks

This overload is equivalent to calling:

boost::asio::async_read_at(
    d, 42, buffers,
    boost::asio::transfer_all(),
    handler);

Start an asynchronous operation to read a certain amount of data at the specified offset.

template<
    typename AsyncRandomAccessReadDevice,
    typename MutableBufferSequence,
    typename CompletionCondition,
    typename ReadHandler>
void-or-deduced async_read_at(
    AsyncRandomAccessReadDevice & d,
    uint64_t offset,
    const MutableBufferSequence & buffers,
    CompletionCondition completion_condition,
    ReadHandler handler);

This function is used to asynchronously read a certain number of bytes of data from a random access device at the specified offset. The function call always returns immediately. The asynchronous operation will continue until one of the following conditions is true:

  • The supplied buffers are full. That is, the bytes transferred is equal to the sum of the buffer sizes.
  • The completion_condition function object returns 0.
Parameters

d

The device from which the data is to be read. The type must support the AsyncRandomAccessReadDevice concept.

offset

The offset at which the data will be read.

buffers

One or more buffers into which the data will be read. The sum of the buffer sizes indicates the maximum number of bytes to read from the device. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

completion_condition

The function object to be called to determine whether the read operation is complete. The signature of the function object must be:

std::size_t completion_condition(
  // Result of latest async_read_some_at operation.
  const boost::system::error_code& error,

  // Number of bytes transferred so far.
  std::size_t bytes_transferred
);

A return value of 0 indicates that the read operation is complete. A non-zero return value indicates the maximum number of bytes to be read on the next call to the device's async_read_some_at function.

handler

The handler to be called when the read operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  // Result of operation.
  const boost::system::error_code& error,

  // Number of bytes copied into the buffers. If an error
  // occurred, this will be the number of bytes successfully
  // transferred prior to the error.
  std::size_t bytes_transferred
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Example

To read into a single data buffer use the buffer function as follows:

boost::asio::async_read_at(d, 42,
    boost::asio::buffer(data, size),
    boost::asio::transfer_at_least(32),
    handler);

See the buffer documentation for information on reading into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Start an asynchronous operation to read a certain amount of data at the specified offset.

template<
    typename AsyncRandomAccessReadDevice,
    typename Allocator,
    typename ReadHandler>
void-or-deduced async_read_at(
    AsyncRandomAccessReadDevice & d,
    uint64_t offset,
    basic_streambuf< Allocator > & b,
    ReadHandler handler);

This function is used to asynchronously read a certain number of bytes of data from a random access device at the specified offset. The function call always returns immediately. The asynchronous operation will continue until one of the following conditions is true:

  • An error occurred.

This operation is implemented in terms of zero or more calls to the device's async_read_some_at function.

Parameters

d

The device from which the data is to be read. The type must support the AsyncRandomAccessReadDevice concept.

offset

The offset at which the data will be read.

b

A basic_streambuf object into which the data will be read. Ownership of the streambuf is retained by the caller, which must guarantee that it remains valid until the handler is called.

handler

The handler to be called when the read operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  // Result of operation.
  const boost::system::error_code& error,

  // Number of bytes copied into the buffers. If an error
  // occurred, this will be the number of bytes successfully
  // transferred prior to the error.
  std::size_t bytes_transferred
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

This overload is equivalent to calling:

boost::asio::async_read_at(
    d, 42, b,
    boost::asio::transfer_all(),
    handler);

Start an asynchronous operation to read a certain amount of data at the specified offset.

template<
    typename AsyncRandomAccessReadDevice,
    typename Allocator,
    typename CompletionCondition,
    typename ReadHandler>
void-or-deduced async_read_at(
    AsyncRandomAccessReadDevice & d,
    uint64_t offset,
    basic_streambuf< Allocator > & b,
    CompletionCondition completion_condition,
    ReadHandler handler);

This function is used to asynchronously read a certain number of bytes of data from a random access device at the specified offset. The function call always returns immediately. The asynchronous operation will continue until one of the following conditions is true:

  • The completion_condition function object returns 0.

This operation is implemented in terms of zero or more calls to the device's async_read_some_at function.

Parameters

d

The device from which the data is to be read. The type must support the AsyncRandomAccessReadDevice concept.

offset

The offset at which the data will be read.

b

A basic_streambuf object into which the data will be read. Ownership of the streambuf is retained by the caller, which must guarantee that it remains valid until the handler is called.

completion_condition

The function object to be called to determine whether the read operation is complete. The signature of the function object must be:

std::size_t completion_condition(
  // Result of latest async_read_some_at operation.
  const boost::system::error_code& error,

  // Number of bytes transferred so far.
  std::size_t bytes_transferred
);

A return value of 0 indicates that the read operation is complete. A non-zero return value indicates the maximum number of bytes to be read on the next call to the device's async_read_some_at function.

handler

The handler to be called when the read operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  // Result of operation.
  const boost::system::error_code& error,

  // Number of bytes copied into the buffers. If an error
  // occurred, this will be the number of bytes successfully
  // transferred prior to the error.
  std::size_t bytes_transferred
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Start an asynchronous operation to read data into a streambuf until it contains a delimiter, matches a regular expression, or a function object indicates a match.

template<
    typename AsyncReadStream,
    typename Allocator,
    typename ReadHandler>
void-or-deduced async_read_until(
    AsyncReadStream & s,
    boost::asio::basic_streambuf< Allocator > & b,
    char delim,
    ReadHandler handler);
  » more...

template<
    typename AsyncReadStream,
    typename Allocator,
    typename ReadHandler>
void-or-deduced async_read_until(
    AsyncReadStream & s,
    boost::asio::basic_streambuf< Allocator > & b,
    const std::string & delim,
    ReadHandler handler);
  » more...

template<
    typename AsyncReadStream,
    typename Allocator,
    typename ReadHandler>
void-or-deduced async_read_until(
    AsyncReadStream & s,
    boost::asio::basic_streambuf< Allocator > & b,
    const boost::regex & expr,
    ReadHandler handler);
  » more...

template<
    typename AsyncReadStream,
    typename Allocator,
    typename MatchCondition,
    typename ReadHandler>
void-or-deduced async_read_until(
    AsyncReadStream & s,
    boost::asio::basic_streambuf< Allocator > & b,
    MatchCondition match_condition,
    ReadHandler handler,
    typename enable_if< is_match_condition< MatchCondition >::value >::type *  = 0);
  » more...
Requirements

Header: boost/asio/read_until.hpp

Convenience header: boost/asio.hpp

Start an asynchronous operation to read data into a streambuf until it contains a specified delimiter.

template<
    typename AsyncReadStream,
    typename Allocator,
    typename ReadHandler>
void-or-deduced async_read_until(
    AsyncReadStream & s,
    boost::asio::basic_streambuf< Allocator > & b,
    char delim,
    ReadHandler handler);

This function is used to asynchronously read data into the specified streambuf until the streambuf's get area contains the specified delimiter. The function call always returns immediately. The asynchronous operation will continue until one of the following conditions is true:

  • The get area of the streambuf contains the specified delimiter.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the stream's async_read_some function, and is known as a composed operation. If the streambuf's get area already contains the delimiter, this asynchronous operation completes immediately. The program must ensure that the stream performs no other read operations (such as async_read, async_read_until, the stream's async_read_some function, or any other composed operations that perform reads) until this operation completes.

Parameters

s

The stream from which the data is to be read. The type must support the AsyncReadStream concept.

b

A streambuf object into which the data will be read. Ownership of the streambuf is retained by the caller, which must guarantee that it remains valid until the handler is called.

delim

The delimiter character.

handler

The handler to be called when the read operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  // Result of operation.
  const boost::system::error_code& error,

  // The number of bytes in the streambuf's get
  // area up to and including the delimiter.
  // 0 if an error occurred.
  std::size_t bytes_transferred
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

After a successful async_read_until operation, the streambuf may contain additional data beyond the delimiter. An application will typically leave that data in the streambuf for a subsequent async_read_until operation to examine.

Example

To asynchronously read data into a streambuf until a newline is encountered:

boost::asio::streambuf b;
...
void handler(const boost::system::error_code& e, std::size_t size)
{
  if (!e)
  {
    std::istream is(&b);
    std::string line;
    std::getline(is, line);
    ...
  }
}
...
boost::asio::async_read_until(s, b, '\n', handler);

After the async_read_until operation completes successfully, the buffer b contains the delimiter:

{ 'a', 'b', ..., 'c', '\n', 'd', 'e', ... }

The call to std::getline then extracts the data up to and including the delimiter, so that the string line contains:

{ 'a', 'b', ..., 'c', '\n' }

The remaining data is left in the buffer b as follows:

{ 'd', 'e', ... }

This data may be the start of a new line, to be extracted by a subsequent async_read_until operation.

Start an asynchronous operation to read data into a streambuf until it contains a specified delimiter.

template<
    typename AsyncReadStream,
    typename Allocator,
    typename ReadHandler>
void-or-deduced async_read_until(
    AsyncReadStream & s,
    boost::asio::basic_streambuf< Allocator > & b,
    const std::string & delim,
    ReadHandler handler);

This function is used to asynchronously read data into the specified streambuf until the streambuf's get area contains the specified delimiter. The function call always returns immediately. The asynchronous operation will continue until one of the following conditions is true:

  • The get area of the streambuf contains the specified delimiter.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the stream's async_read_some function, and is known as a composed operation. If the streambuf's get area already contains the delimiter, this asynchronous operation completes immediately. The program must ensure that the stream performs no other read operations (such as async_read, async_read_until, the stream's async_read_some function, or any other composed operations that perform reads) until this operation completes.

Parameters

s

The stream from which the data is to be read. The type must support the AsyncReadStream concept.

b

A streambuf object into which the data will be read. Ownership of the streambuf is retained by the caller, which must guarantee that it remains valid until the handler is called.

delim

The delimiter string.

handler

The handler to be called when the read operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  // Result of operation.
  const boost::system::error_code& error,

  // The number of bytes in the streambuf's get
  // area up to and including the delimiter.
  // 0 if an error occurred.
  std::size_t bytes_transferred
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

After a successful async_read_until operation, the streambuf may contain additional data beyond the delimiter. An application will typically leave that data in the streambuf for a subsequent async_read_until operation to examine.

Example

To asynchronously read data into a streambuf until a newline is encountered:

boost::asio::streambuf b;
...
void handler(const boost::system::error_code& e, std::size_t size)
{
  if (!e)
  {
    std::istream is(&b);
    std::string line;
    std::getline(is, line);
    ...
  }
}
...
boost::asio::async_read_until(s, b, "\r\n", handler);

After the async_read_until operation completes successfully, the buffer b contains the delimiter:

{ 'a', 'b', ..., 'c', '\r', '\n', 'd', 'e', ... }

The call to std::getline then extracts the data up to and including the delimiter, so that the string line contains:

{ 'a', 'b', ..., 'c', '\r', '\n' }

The remaining data is left in the buffer b as follows:

{ 'd', 'e', ... }

This data may be the start of a new line, to be extracted by a subsequent async_read_until operation.

Start an asynchronous operation to read data into a streambuf until some part of its data matches a regular expression.

template<
    typename AsyncReadStream,
    typename Allocator,
    typename ReadHandler>
void-or-deduced async_read_until(
    AsyncReadStream & s,
    boost::asio::basic_streambuf< Allocator > & b,
    const boost::regex & expr,
    ReadHandler handler);

This function is used to asynchronously read data into the specified streambuf until the streambuf's get area contains some data that matches a regular expression. The function call always returns immediately. The asynchronous operation will continue until one of the following conditions is true:

  • A substring of the streambuf's get area matches the regular expression.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the stream's async_read_some function, and is known as a composed operation. If the streambuf's get area already contains data that matches the regular expression, this asynchronous operation completes immediately. The program must ensure that the stream performs no other read operations (such as async_read, async_read_until, the stream's async_read_some function, or any other composed operations that perform reads) until this operation completes.

Parameters

s

The stream from which the data is to be read. The type must support the AsyncReadStream concept.

b

A streambuf object into which the data will be read. Ownership of the streambuf is retained by the caller, which must guarantee that it remains valid until the handler is called.

expr

The regular expression.

handler

The handler to be called when the read operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  // Result of operation.
  const boost::system::error_code& error,

  // The number of bytes in the streambuf's get
  // area up to and including the substring
  // that matches the regular. expression.
  // 0 if an error occurred.
  std::size_t bytes_transferred
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

After a successful async_read_until operation, the streambuf may contain additional data beyond that which matched the regular expression. An application will typically leave that data in the streambuf for a subsequent async_read_until operation to examine.

Example

To asynchronously read data into a streambuf until a CR-LF sequence is encountered:

boost::asio::streambuf b;
...
void handler(const boost::system::error_code& e, std::size_t size)
{
  if (!e)
  {
    std::istream is(&b);
    std::string line;
    std::getline(is, line);
    ...
  }
}
...
boost::asio::async_read_until(s, b, boost::regex("\r\n"), handler);

After the async_read_until operation completes successfully, the buffer b contains the data which matched the regular expression:

{ 'a', 'b', ..., 'c', '\r', '\n', 'd', 'e', ... }

The call to std::getline then extracts the data up to and including the match, so that the string line contains:

{ 'a', 'b', ..., 'c', '\r', '\n' }

The remaining data is left in the buffer b as follows:

{ 'd', 'e', ... }

This data may be the start of a new line, to be extracted by a subsequent async_read_until operation.

Start an asynchronous operation to read data into a streambuf until a function object indicates a match.

template<
    typename AsyncReadStream,
    typename Allocator,
    typename MatchCondition,
    typename ReadHandler>
void-or-deduced async_read_until(
    AsyncReadStream & s,
    boost::asio::basic_streambuf< Allocator > & b,
    MatchCondition match_condition,
    ReadHandler handler,
    typename enable_if< is_match_condition< MatchCondition >::value >::type *  = 0);

This function is used to asynchronously read data into the specified streambuf until a user-defined match condition function object, when applied to the data contained in the streambuf, indicates a successful match. The function call always returns immediately. The asynchronous operation will continue until one of the following conditions is true:

  • The match condition function object returns a std::pair where the second element evaluates to true.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the stream's async_read_some function, and is known as a composed operation. If the match condition function object already indicates a match, this asynchronous operation completes immediately. The program must ensure that the stream performs no other read operations (such as async_read, async_read_until, the stream's async_read_some function, or any other composed operations that perform reads) until this operation completes.

Parameters

s

The stream from which the data is to be read. The type must support the AsyncReadStream concept.

b

A streambuf object into which the data will be read.

match_condition

The function object to be called to determine whether a match exists. The signature of the function object must be:

pair<iterator, bool> match_condition(iterator begin, iterator end);

where iterator represents the type:

buffers_iterator<basic_streambuf<Allocator>::const_buffers_type>

The iterator parameters begin and end define the range of bytes to be scanned to determine whether there is a match. The first member of the return value is an iterator marking one-past-the-end of the bytes that have been consumed by the match function. This iterator is used to calculate the begin parameter for any subsequent invocation of the match condition. The second member of the return value is true if a match has been found, false otherwise.

handler

The handler to be called when the read operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  // Result of operation.
  const boost::system::error_code& error,

  // The number of bytes in the streambuf's get
  // area that have been fully consumed by the
  // match function. O if an error occurred.
  std::size_t bytes_transferred
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

After a successful async_read_until operation, the streambuf may contain additional data beyond that which matched the function object. An application will typically leave that data in the streambuf for a subsequent async_read_until operation to examine.

The default implementation of the is_match_condition type trait evaluates to true for function pointers and function objects with a result_type typedef. It must be specialised for other user-defined function objects.

Examples

To asynchronously read data into a streambuf until whitespace is encountered:

typedef boost::asio::buffers_iterator<
    boost::asio::streambuf::const_buffers_type> iterator;

std::pair<iterator, bool>
match_whitespace(iterator begin, iterator end)
{
  iterator i = begin;
  while (i != end)
    if (std::isspace(*i++))
      return std::make_pair(i, true);
  return std::make_pair(i, false);
}
...
void handler(const boost::system::error_code& e, std::size_t size);
...
boost::asio::streambuf b;
boost::asio::async_read_until(s, b, match_whitespace, handler);

To asynchronously read data into a streambuf until a matching character is found:

class match_char
{
public:
  explicit match_char(char c) : c_(c) {}

  template <typename Iterator>
  std::pair<Iterator, bool> operator()(
      Iterator begin, Iterator end) const
  {
    Iterator i = begin;
    while (i != end)
      if (c_ == *i++)
        return std::make_pair(i, true);
    return std::make_pair(i, false);
  }

private:
  char c_;
};

namespace asio {
  template <> struct is_match_condition<match_char>
    : public boost::true_type {};
} // namespace asio
...
void handler(const boost::system::error_code& e, std::size_t size);
...
boost::asio::streambuf b;
boost::asio::async_read_until(s, b, match_char('a'), handler);

An interface for customising the behaviour of an initiating function.

template<
    typename Handler>
class async_result
Types

Name

Description

type

The return type of the initiating function.

Member Functions

Name

Description

async_result

Construct an async result from a given handler.

get

Obtain the value to be returned from the initiating function.

This template may be specialised for user-defined handler types.

Requirements

Header: boost/asio/async_result.hpp

Convenience header: boost/asio.hpp

Construct an async result from a given handler.

async_result(
    Handler & );

When using a specalised async_result, the constructor has an opportunity to initialise some state associated with the handler, which is then returned from the initiating function.

Obtain the value to be returned from the initiating function.

type get();

The return type of the initiating function.

typedef void type;
Requirements

Header: boost/asio/async_result.hpp

Convenience header: boost/asio.hpp

Start an asynchronous operation to write a certain amount of data to a stream.

template<
    typename AsyncWriteStream,
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_write(
    AsyncWriteStream & s,
    const ConstBufferSequence & buffers,
    WriteHandler handler);
  » more...

template<
    typename AsyncWriteStream,
    typename ConstBufferSequence,
    typename CompletionCondition,
    typename WriteHandler>
void-or-deduced async_write(
    AsyncWriteStream & s,
    const ConstBufferSequence & buffers,
    CompletionCondition completion_condition,
    WriteHandler handler);
  » more...

template<
    typename AsyncWriteStream,
    typename Allocator,
    typename WriteHandler>
void-or-deduced async_write(
    AsyncWriteStream & s,
    basic_streambuf< Allocator > & b,
    WriteHandler handler);
  » more...

template<
    typename AsyncWriteStream,
    typename Allocator,
    typename CompletionCondition,
    typename WriteHandler>
void-or-deduced async_write(
    AsyncWriteStream & s,
    basic_streambuf< Allocator > & b,
    CompletionCondition completion_condition,
    WriteHandler handler);
  » more...
Requirements

Header: boost/asio/write.hpp

Convenience header: boost/asio.hpp

Start an asynchronous operation to write all of the supplied data to a stream.

template<
    typename AsyncWriteStream,
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_write(
    AsyncWriteStream & s,
    const ConstBufferSequence & buffers,
    WriteHandler handler);

This function is used to asynchronously write a certain number of bytes of data to a stream. The function call always returns immediately. The asynchronous operation will continue until one of the following conditions is true:

  • All of the data in the supplied buffers has been written. That is, the bytes transferred is equal to the sum of the buffer sizes.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the stream's async_write_some function, and is known as a composed operation. The program must ensure that the stream performs no other write operations (such as async_write, the stream's async_write_some function, or any other composed operations that perform writes) until this operation completes.

Parameters

s

The stream to which the data is to be written. The type must support the AsyncWriteStream concept.

buffers

One or more buffers containing the data to be written. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

handler

The handler to be called when the write operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.

  std::size_t bytes_transferred           // Number of bytes written from the
                                          // buffers. If an error occurred,
                                          // this will be less than the sum
                                          // of the buffer sizes.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Example

To write a single data buffer use the buffer function as follows:

boost::asio::async_write(s, boost::asio::buffer(data, size), handler);

See the buffer documentation for information on writing multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Start an asynchronous operation to write a certain amount of data to a stream.

template<
    typename AsyncWriteStream,
    typename ConstBufferSequence,
    typename CompletionCondition,
    typename WriteHandler>
void-or-deduced async_write(
    AsyncWriteStream & s,
    const ConstBufferSequence & buffers,
    CompletionCondition completion_condition,
    WriteHandler handler);

This function is used to asynchronously write a certain number of bytes of data to a stream. The function call always returns immediately. The asynchronous operation will continue until one of the following conditions is true:

  • All of the data in the supplied buffers has been written. That is, the bytes transferred is equal to the sum of the buffer sizes.
  • The completion_condition function object returns 0.

This operation is implemented in terms of zero or more calls to the stream's async_write_some function, and is known as a composed operation. The program must ensure that the stream performs no other write operations (such as async_write, the stream's async_write_some function, or any other composed operations that perform writes) until this operation completes.

Parameters

s

The stream to which the data is to be written. The type must support the AsyncWriteStream concept.

buffers

One or more buffers containing the data to be written. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

completion_condition

The function object to be called to determine whether the write operation is complete. The signature of the function object must be:

std::size_t completion_condition(
  // Result of latest async_write_some operation.
  const boost::system::error_code& error,

  // Number of bytes transferred so far.
  std::size_t bytes_transferred
);

A return value of 0 indicates that the write operation is complete. A non-zero return value indicates the maximum number of bytes to be written on the next call to the stream's async_write_some function.

handler

The handler to be called when the write operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.

  std::size_t bytes_transferred           // Number of bytes written from the
                                          // buffers. If an error occurred,
                                          // this will be less than the sum
                                          // of the buffer sizes.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Example

To write a single data buffer use the buffer function as follows:

boost::asio::async_write(s,
    boost::asio::buffer(data, size),
    boost::asio::transfer_at_least(32),
    handler);

See the buffer documentation for information on writing multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Start an asynchronous operation to write all of the supplied data to a stream.

template<
    typename AsyncWriteStream,
    typename Allocator,
    typename WriteHandler>
void-or-deduced async_write(
    AsyncWriteStream & s,
    basic_streambuf< Allocator > & b,
    WriteHandler handler);

This function is used to asynchronously write a certain number of bytes of data to a stream. The function call always returns immediately. The asynchronous operation will continue until one of the following conditions is true:

  • All of the data in the supplied basic_streambuf has been written.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the stream's async_write_some function, and is known as a composed operation. The program must ensure that the stream performs no other write operations (such as async_write, the stream's async_write_some function, or any other composed operations that perform writes) until this operation completes.

Parameters

s

The stream to which the data is to be written. The type must support the AsyncWriteStream concept.

b

A basic_streambuf object from which data will be written. Ownership of the streambuf is retained by the caller, which must guarantee that it remains valid until the handler is called.

handler

The handler to be called when the write operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.

  std::size_t bytes_transferred           // Number of bytes written from the
                                          // buffers. If an error occurred,
                                          // this will be less than the sum
                                          // of the buffer sizes.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Start an asynchronous operation to write a certain amount of data to a stream.

template<
    typename AsyncWriteStream,
    typename Allocator,
    typename CompletionCondition,
    typename WriteHandler>
void-or-deduced async_write(
    AsyncWriteStream & s,
    basic_streambuf< Allocator > & b,
    CompletionCondition completion_condition,
    WriteHandler handler);

This function is used to asynchronously write a certain number of bytes of data to a stream. The function call always returns immediately. The asynchronous operation will continue until one of the following conditions is true:

  • All of the data in the supplied basic_streambuf has been written.
  • The completion_condition function object returns 0.

This operation is implemented in terms of zero or more calls to the stream's async_write_some function, and is known as a composed operation. The program must ensure that the stream performs no other write operations (such as async_write, the stream's async_write_some function, or any other composed operations that perform writes) until this operation completes.

Parameters

s

The stream to which the data is to be written. The type must support the AsyncWriteStream concept.

b

A basic_streambuf object from which data will be written. Ownership of the streambuf is retained by the caller, which must guarantee that it remains valid until the handler is called.

completion_condition

The function object to be called to determine whether the write operation is complete. The signature of the function object must be:

std::size_t completion_condition(
  // Result of latest async_write_some operation.
  const boost::system::error_code& error,

  // Number of bytes transferred so far.
  std::size_t bytes_transferred
);

A return value of 0 indicates that the write operation is complete. A non-zero return value indicates the maximum number of bytes to be written on the next call to the stream's async_write_some function.

handler

The handler to be called when the write operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.

  std::size_t bytes_transferred           // Number of bytes written from the
                                          // buffers. If an error occurred,
                                          // this will be less than the sum
                                          // of the buffer sizes.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Start an asynchronous operation to write a certain amount of data at the specified offset.

template<
    typename AsyncRandomAccessWriteDevice,
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_write_at(
    AsyncRandomAccessWriteDevice & d,
    uint64_t offset,
    const ConstBufferSequence & buffers,
    WriteHandler handler);
  » more...

template<
    typename AsyncRandomAccessWriteDevice,
    typename ConstBufferSequence,
    typename CompletionCondition,
    typename WriteHandler>
void-or-deduced async_write_at(
    AsyncRandomAccessWriteDevice & d,
    uint64_t offset,
    const ConstBufferSequence & buffers,
    CompletionCondition completion_condition,
    WriteHandler handler);
  » more...

template<
    typename AsyncRandomAccessWriteDevice,
    typename Allocator,
    typename WriteHandler>
void-or-deduced async_write_at(
    AsyncRandomAccessWriteDevice & d,
    uint64_t offset,
    basic_streambuf< Allocator > & b,
    WriteHandler handler);
  » more...

template<
    typename AsyncRandomAccessWriteDevice,
    typename Allocator,
    typename CompletionCondition,
    typename WriteHandler>
void-or-deduced async_write_at(
    AsyncRandomAccessWriteDevice & d,
    uint64_t offset,
    basic_streambuf< Allocator > & b,
    CompletionCondition completion_condition,
    WriteHandler handler);
  » more...
Requirements

Header: boost/asio/write_at.hpp

Convenience header: boost/asio.hpp

Start an asynchronous operation to write all of the supplied data at the specified offset.

template<
    typename AsyncRandomAccessWriteDevice,
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_write_at(
    AsyncRandomAccessWriteDevice & d,
    uint64_t offset,
    const ConstBufferSequence & buffers,
    WriteHandler handler);

This function is used to asynchronously write a certain number of bytes of data to a random access device at a specified offset. The function call always returns immediately. The asynchronous operation will continue until one of the following conditions is true:

  • All of the data in the supplied buffers has been written. That is, the bytes transferred is equal to the sum of the buffer sizes.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the device's async_write_some_at function, and is known as a composed operation. The program must ensure that the device performs no overlapping write operations (such as async_write_at, the device's async_write_some_at function, or any other composed operations that perform writes) until this operation completes. Operations are overlapping if the regions defined by their offsets, and the numbers of bytes to write, intersect.

Parameters

d

The device to which the data is to be written. The type must support the AsyncRandomAccessWriteDevice concept.

offset

The offset at which the data will be written.

buffers

One or more buffers containing the data to be written. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

handler

The handler to be called when the write operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  // Result of operation.
  const boost::system::error_code& error,

  // Number of bytes written from the buffers. If an error
  // occurred, this will be less than the sum of the buffer sizes.
  std::size_t bytes_transferred
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Example

To write a single data buffer use the buffer function as follows:

boost::asio::async_write_at(d, 42, boost::asio::buffer(data, size), handler);

See the buffer documentation for information on writing multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Start an asynchronous operation to write a certain amount of data at the specified offset.

template<
    typename AsyncRandomAccessWriteDevice,
    typename ConstBufferSequence,
    typename CompletionCondition,
    typename WriteHandler>
void-or-deduced async_write_at(
    AsyncRandomAccessWriteDevice & d,
    uint64_t offset,
    const ConstBufferSequence & buffers,
    CompletionCondition completion_condition,
    WriteHandler handler);

This function is used to asynchronously write a certain number of bytes of data to a random access device at a specified offset. The function call always returns immediately. The asynchronous operation will continue until one of the following conditions is true:

  • All of the data in the supplied buffers has been written. That is, the bytes transferred is equal to the sum of the buffer sizes.
  • The completion_condition function object returns 0.

This operation is implemented in terms of zero or more calls to the device's async_write_some_at function, and is known as a composed operation. The program must ensure that the device performs no overlapping write operations (such as async_write_at, the device's async_write_some_at function, or any other composed operations that perform writes) until this operation completes. Operations are overlapping if the regions defined by their offsets, and the numbers of bytes to write, intersect.

Parameters

d

The device to which the data is to be written. The type must support the AsyncRandomAccessWriteDevice concept.

offset

The offset at which the data will be written.

buffers

One or more buffers containing the data to be written. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

completion_condition

The function object to be called to determine whether the write operation is complete. The signature of the function object must be:

std::size_t completion_condition(
  // Result of latest async_write_some_at operation.
  const boost::system::error_code& error,

  // Number of bytes transferred so far.
  std::size_t bytes_transferred
);

A return value of 0 indicates that the write operation is complete. A non-zero return value indicates the maximum number of bytes to be written on the next call to the device's async_write_some_at function.

handler

The handler to be called when the write operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  // Result of operation.
  const boost::system::error_code& error,

  // Number of bytes written from the buffers. If an error
  // occurred, this will be less than the sum of the buffer sizes.
  std::size_t bytes_transferred
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Example

To write a single data buffer use the buffer function as follows:

boost::asio::async_write_at(d, 42,
    boost::asio::buffer(data, size),
    boost::asio::transfer_at_least(32),
    handler);

See the buffer documentation for information on writing multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Start an asynchronous operation to write all of the supplied data at the specified offset.

template<
    typename AsyncRandomAccessWriteDevice,
    typename Allocator,
    typename WriteHandler>
void-or-deduced async_write_at(
    AsyncRandomAccessWriteDevice & d,
    uint64_t offset,
    basic_streambuf< Allocator > & b,
    WriteHandler handler);

This function is used to asynchronously write a certain number of bytes of data to a random access device at a specified offset. The function call always returns immediately. The asynchronous operation will continue until one of the following conditions is true:

  • All of the data in the supplied basic_streambuf has been written.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the device's async_write_some_at function, and is known as a composed operation. The program must ensure that the device performs no overlapping write operations (such as async_write_at, the device's async_write_some_at function, or any other composed operations that perform writes) until this operation completes. Operations are overlapping if the regions defined by their offsets, and the numbers of bytes to write, intersect.

Parameters

d

The device to which the data is to be written. The type must support the AsyncRandomAccessWriteDevice concept.

offset

The offset at which the data will be written.

b

A basic_streambuf object from which data will be written. Ownership of the streambuf is retained by the caller, which must guarantee that it remains valid until the handler is called.

handler

The handler to be called when the write operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  // Result of operation.
  const boost::system::error_code& error,

  // Number of bytes written from the buffers. If an error
  // occurred, this will be less than the sum of the buffer sizes.
  std::size_t bytes_transferred
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Start an asynchronous operation to write a certain amount of data at the specified offset.

template<
    typename AsyncRandomAccessWriteDevice,
    typename Allocator,
    typename CompletionCondition,
    typename WriteHandler>
void-or-deduced async_write_at(
    AsyncRandomAccessWriteDevice & d,
    uint64_t offset,
    basic_streambuf< Allocator > & b,
    CompletionCondition completion_condition,
    WriteHandler handler);

This function is used to asynchronously write a certain number of bytes of data to a random access device at a specified offset. The function call always returns immediately. The asynchronous operation will continue until one of the following conditions is true:

  • All of the data in the supplied basic_streambuf has been written.
  • The completion_condition function object returns 0.

This operation is implemented in terms of zero or more calls to the device's async_write_some_at function, and is known as a composed operation. The program must ensure that the device performs no overlapping write operations (such as async_write_at, the device's async_write_some_at function, or any other composed operations that perform writes) until this operation completes. Operations are overlapping if the regions defined by their offsets, and the numbers of bytes to write, intersect.

Parameters

d

The device to which the data is to be written. The type must support the AsyncRandomAccessWriteDevice concept.

offset

The offset at which the data will be written.

b

A basic_streambuf object from which data will be written. Ownership of the streambuf is retained by the caller, which must guarantee that it remains valid until the handler is called.

completion_condition

The function object to be called to determine whether the write operation is complete. The signature of the function object must be:

std::size_t completion_condition(
  // Result of latest async_write_some_at operation.
  const boost::system::error_code& error,

  // Number of bytes transferred so far.
  std::size_t bytes_transferred
);

A return value of 0 indicates that the write operation is complete. A non-zero return value indicates the maximum number of bytes to be written on the next call to the device's async_write_some_at function.

handler

The handler to be called when the write operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  // Result of operation.
  const boost::system::error_code& error,

  // Number of bytes written from the buffers. If an error
  // occurred, this will be less than the sum of the buffer sizes.
  std::size_t bytes_transferred
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

basic_datagram_socket::assign
basic_datagram_socket::async_connect
basic_datagram_socket::async_receive
basic_datagram_socket::async_receive_from
basic_datagram_socket::async_send
basic_datagram_socket::async_send_to
basic_datagram_socket::at_mark
basic_datagram_socket::available
basic_datagram_socket::basic_datagram_socket
basic_datagram_socket::bind
basic_datagram_socket::broadcast
basic_datagram_socket::bytes_readable
basic_datagram_socket::cancel
basic_datagram_socket::close
basic_datagram_socket::connect
basic_datagram_socket::debug
basic_datagram_socket::do_not_route
basic_datagram_socket::enable_connection_aborted
basic_datagram_socket::endpoint_type
basic_datagram_socket::get_implementation
basic_datagram_socket::get_io_service
basic_datagram_socket::get_option
basic_datagram_socket::get_service
basic_datagram_socket::implementation
basic_datagram_socket::implementation_type
basic_datagram_socket::io_control
basic_datagram_socket::is_open
basic_datagram_socket::keep_alive
basic_datagram_socket::linger
basic_datagram_socket::local_endpoint
basic_datagram_socket::lowest_layer
basic_datagram_socket::lowest_layer_type
basic_datagram_socket::max_connections
basic_datagram_socket::message_do_not_route
basic_datagram_socket::message_end_of_record
basic_datagram_socket::message_flags
basic_datagram_socket::message_out_of_band
basic_datagram_socket::message_peek
basic_datagram_socket::native
basic_datagram_socket::native_handle
basic_datagram_socket::native_handle_type
basic_datagram_socket::native_non_blocking
basic_datagram_socket::native_type
basic_datagram_socket::non_blocking
basic_datagram_socket::non_blocking_io
basic_datagram_socket::open
basic_datagram_socket::operator=
basic_datagram_socket::protocol_type
basic_datagram_socket::receive
basic_datagram_socket::receive_buffer_size
basic_datagram_socket::receive_from
basic_datagram_socket::receive_low_watermark
basic_datagram_socket::remote_endpoint
basic_datagram_socket::reuse_address
basic_datagram_socket::send
basic_datagram_socket::send_buffer_size
basic_datagram_socket::send_low_watermark
basic_datagram_socket::send_to
basic_datagram_socket::service
basic_datagram_socket::service_type
basic_datagram_socket::set_option
basic_datagram_socket::shutdown
basic_datagram_socket::shutdown_type

Provides datagram-oriented socket functionality.

template<
    typename Protocol,
    typename DatagramSocketService = datagram_socket_service<Protocol>>
class basic_datagram_socket :
  public basic_socket< Protocol, DatagramSocketService >
Types

Name

Description

broadcast

Socket option to permit sending of broadcast messages.

bytes_readable

IO control command to get the amount of data that can be read without blocking.

debug

Socket option to enable socket-level debugging.

do_not_route

Socket option to prevent routing, use local interfaces only.

enable_connection_aborted

Socket option to report aborted connections on accept.

endpoint_type

The endpoint type.

implementation_type

The underlying implementation type of I/O object.

keep_alive

Socket option to send keep-alives.

linger

Socket option to specify whether the socket lingers on close if unsent data is present.

lowest_layer_type

A basic_socket is always the lowest layer.

message_flags

Bitmask type for flags that can be passed to send and receive operations.

native_handle_type

The native representation of a socket.

native_type

(Deprecated: Use native_handle_type.) The native representation of a socket.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

protocol_type

The protocol type.

receive_buffer_size

Socket option for the receive buffer size of a socket.

receive_low_watermark

Socket option for the receive low watermark.

reuse_address

Socket option to allow the socket to be bound to an address that is already in use.

send_buffer_size

Socket option for the send buffer size of a socket.

send_low_watermark

Socket option for the send low watermark.

service_type

The type of the service that will be used to provide I/O operations.

shutdown_type

Different ways a socket may be shutdown.

Member Functions

Name

Description

assign

Assign an existing native socket to the socket.

async_connect

Start an asynchronous connect.

async_receive

Start an asynchronous receive on a connected socket.

async_receive_from

Start an asynchronous receive.

async_send

Start an asynchronous send on a connected socket.

async_send_to

Start an asynchronous send.

at_mark

Determine whether the socket is at the out-of-band data mark.

available

Determine the number of bytes available for reading.

basic_datagram_socket

Construct a basic_datagram_socket without opening it.

Construct and open a basic_datagram_socket.

Construct a basic_datagram_socket, opening it and binding it to the given local endpoint.

Construct a basic_datagram_socket on an existing native socket.

Move-construct a basic_datagram_socket from another.

Move-construct a basic_datagram_socket from a socket of another protocol type.

bind

Bind the socket to the given local endpoint.

cancel

Cancel all asynchronous operations associated with the socket.

close

Close the socket.

connect

Connect the socket to the specified endpoint.

get_io_service

Get the io_service associated with the object.

get_option

Get an option from the socket.

io_control

Perform an IO control command on the socket.

is_open

Determine whether the socket is open.

local_endpoint

Get the local endpoint of the socket.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native socket representation.

native_handle

Get the native socket representation.

native_non_blocking

Gets the non-blocking mode of the native socket implementation.

Sets the non-blocking mode of the native socket implementation.

non_blocking

Gets the non-blocking mode of the socket.

Sets the non-blocking mode of the socket.

open

Open the socket using the specified protocol.

operator=

Move-assign a basic_datagram_socket from another.

Move-assign a basic_datagram_socket from a socket of another protocol type.

receive

Receive some data on a connected socket.

receive_from

Receive a datagram with the endpoint of the sender.

remote_endpoint

Get the remote endpoint of the socket.

send

Send some data on a connected socket.

send_to

Send a datagram to the specified endpoint.

set_option

Set an option on the socket.

shutdown

Disable sends or receives on the socket.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Data Members

Name

Description

max_connections

The maximum length of the queue of pending incoming connections.

message_do_not_route

Specify that the data should not be subject to routing.

message_end_of_record

Specifies that the data marks the end of a record.

message_out_of_band

Process out-of-band data.

message_peek

Peek at incoming data without removing it from the input queue.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_datagram_socket class template provides asynchronous and blocking datagram-oriented socket functionality.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/basic_datagram_socket.hpp

Convenience header: boost/asio.hpp

Assign an existing native socket to the socket.

void assign(
    const protocol_type & protocol,
    const native_handle_type & native_socket);
  » more...

boost::system::error_code assign(
    const protocol_type & protocol,
    const native_handle_type & native_socket,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Assign an existing native socket to the socket.

void assign(
    const protocol_type & protocol,
    const native_handle_type & native_socket);

Inherited from basic_socket.

Assign an existing native socket to the socket.

boost::system::error_code assign(
    const protocol_type & protocol,
    const native_handle_type & native_socket,
    boost::system::error_code & ec);

Inherited from basic_socket.

Start an asynchronous connect.

template<
    typename ConnectHandler>
void-or-deduced async_connect(
    const endpoint_type & peer_endpoint,
    ConnectHandler handler);

This function is used to asynchronously connect a socket to the specified remote endpoint. The function call always returns immediately.

The socket is automatically opened if it is not already open. If the connect fails, and the socket was automatically opened, the socket is not returned to the closed state.

Parameters

peer_endpoint

The remote endpoint to which the socket will be connected. Copies will be made of the endpoint object as required.

handler

The handler to be called when the connection operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error // Result of operation
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Example
void connect_handler(const boost::system::error_code& error)
{
  if (!error)
  {
    // Connect succeeded.
  }
}

...

boost::asio::ip::tcp::socket socket(io_service);
boost::asio::ip::tcp::endpoint endpoint(
    boost::asio::ip::address::from_string("1.2.3.4"), 12345);
socket.async_connect(endpoint, connect_handler);

Start an asynchronous receive on a connected socket.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_receive(
    const MutableBufferSequence & buffers,
    ReadHandler handler);
  » more...

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_receive(
    const MutableBufferSequence & buffers,
    socket_base::message_flags flags,
    ReadHandler handler);
  » more...

Start an asynchronous receive on a connected socket.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_receive(
    const MutableBufferSequence & buffers,
    ReadHandler handler);

This function is used to asynchronously receive data from the datagram socket. The function call always returns immediately.

Parameters

buffers

One or more buffers into which the data will be received. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

handler

The handler to be called when the receive operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes received.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

The async_receive operation can only be used with a connected socket. Use the async_receive_from function to receive data on an unconnected datagram socket.

Example

To receive into a single data buffer use the buffer function as follows:

socket.async_receive(boost::asio::buffer(data, size), handler);

See the buffer documentation for information on receiving into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Start an asynchronous receive on a connected socket.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_receive(
    const MutableBufferSequence & buffers,
    socket_base::message_flags flags,
    ReadHandler handler);

This function is used to asynchronously receive data from the datagram socket. The function call always returns immediately.

Parameters

buffers

One or more buffers into which the data will be received. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

flags

Flags specifying how the receive call is to be made.

handler

The handler to be called when the receive operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes received.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

The async_receive operation can only be used with a connected socket. Use the async_receive_from function to receive data on an unconnected datagram socket.

Start an asynchronous receive.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_receive_from(
    const MutableBufferSequence & buffers,
    endpoint_type & sender_endpoint,
    ReadHandler handler);
  » more...

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_receive_from(
    const MutableBufferSequence & buffers,
    endpoint_type & sender_endpoint,
    socket_base::message_flags flags,
    ReadHandler handler);
  » more...

Start an asynchronous receive.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_receive_from(
    const MutableBufferSequence & buffers,
    endpoint_type & sender_endpoint,
    ReadHandler handler);

This function is used to asynchronously receive a datagram. The function call always returns immediately.

Parameters

buffers

One or more buffers into which the data will be received. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

sender_endpoint

An endpoint object that receives the endpoint of the remote sender of the datagram. Ownership of the sender_endpoint object is retained by the caller, which must guarantee that it is valid until the handler is called.

handler

The handler to be called when the receive operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes received.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Example

To receive into a single data buffer use the buffer function as follows:

socket.async_receive_from(
    boost::asio::buffer(data, size), sender_endpoint, handler);

See the buffer documentation for information on receiving into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Start an asynchronous receive.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_receive_from(
    const MutableBufferSequence & buffers,
    endpoint_type & sender_endpoint,
    socket_base::message_flags flags,
    ReadHandler handler);

This function is used to asynchronously receive a datagram. The function call always returns immediately.

Parameters

buffers

One or more buffers into which the data will be received. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

sender_endpoint

An endpoint object that receives the endpoint of the remote sender of the datagram. Ownership of the sender_endpoint object is retained by the caller, which must guarantee that it is valid until the handler is called.

flags

Flags specifying how the receive call is to be made.

handler

The handler to be called when the receive operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes received.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Start an asynchronous send on a connected socket.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_send(
    const ConstBufferSequence & buffers,
    WriteHandler handler);
  » more...

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_send(
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags,
    WriteHandler handler);
  » more...

Start an asynchronous send on a connected socket.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_send(
    const ConstBufferSequence & buffers,
    WriteHandler handler);

This function is used to asynchronously send data on the datagram socket. The function call always returns immediately.

Parameters

buffers

One or more data buffers to be sent on the socket. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

handler

The handler to be called when the send operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes sent.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

The async_send operation can only be used with a connected socket. Use the async_send_to function to send data on an unconnected datagram socket.

Example

To send a single data buffer use the buffer function as follows:

socket.async_send(boost::asio::buffer(data, size), handler);

See the buffer documentation for information on sending multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Start an asynchronous send on a connected socket.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_send(
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags,
    WriteHandler handler);

This function is used to asynchronously send data on the datagram socket. The function call always returns immediately.

Parameters

buffers

One or more data buffers to be sent on the socket. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

flags

Flags specifying how the send call is to be made.

handler

The handler to be called when the send operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes sent.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

The async_send operation can only be used with a connected socket. Use the async_send_to function to send data on an unconnected datagram socket.

Start an asynchronous send.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_send_to(
    const ConstBufferSequence & buffers,
    const endpoint_type & destination,
    WriteHandler handler);
  » more...

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_send_to(
    const ConstBufferSequence & buffers,
    const endpoint_type & destination,
    socket_base::message_flags flags,
    WriteHandler handler);
  » more...

Start an asynchronous send.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_send_to(
    const ConstBufferSequence & buffers,
    const endpoint_type & destination,
    WriteHandler handler);

This function is used to asynchronously send a datagram to the specified remote endpoint. The function call always returns immediately.

Parameters

buffers

One or more data buffers to be sent to the remote endpoint. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

destination

The remote endpoint to which the data will be sent. Copies will be made of the endpoint as required.

handler

The handler to be called when the send operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes sent.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Example

To send a single data buffer use the buffer function as follows:

boost::asio::ip::udp::endpoint destination(
    boost::asio::ip::address::from_string("1.2.3.4"), 12345);
socket.async_send_to(
    boost::asio::buffer(data, size), destination, handler);

See the buffer documentation for information on sending multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Start an asynchronous send.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_send_to(
    const ConstBufferSequence & buffers,
    const endpoint_type & destination,
    socket_base::message_flags flags,
    WriteHandler handler);

This function is used to asynchronously send a datagram to the specified remote endpoint. The function call always returns immediately.

Parameters

buffers

One or more data buffers to be sent to the remote endpoint. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

flags

Flags specifying how the send call is to be made.

destination

The remote endpoint to which the data will be sent. Copies will be made of the endpoint as required.

handler

The handler to be called when the send operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes sent.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Determine whether the socket is at the out-of-band data mark.

bool at_mark() const;
  » more...

bool at_mark(
    boost::system::error_code & ec) const;
  » more...

Inherited from basic_socket.

Determine whether the socket is at the out-of-band data mark.

bool at_mark() const;

This function is used to check whether the socket input is currently positioned at the out-of-band data mark.

Return Value

A bool indicating whether the socket is at the out-of-band data mark.

Exceptions

boost::system::system_error

Thrown on failure.

Inherited from basic_socket.

Determine whether the socket is at the out-of-band data mark.

bool at_mark(
    boost::system::error_code & ec) const;

This function is used to check whether the socket input is currently positioned at the out-of-band data mark.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

A bool indicating whether the socket is at the out-of-band data mark.

Determine the number of bytes available for reading.

std::size_t available() const;
  » more...

std::size_t available(
    boost::system::error_code & ec) const;
  » more...

Inherited from basic_socket.

Determine the number of bytes available for reading.

std::size_t available() const;

This function is used to determine the number of bytes that may be read without blocking.

Return Value

The number of bytes that may be read without blocking, or 0 if an error occurs.

Exceptions

boost::system::system_error

Thrown on failure.

Inherited from basic_socket.

Determine the number of bytes available for reading.

std::size_t available(
    boost::system::error_code & ec) const;

This function is used to determine the number of bytes that may be read without blocking.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes that may be read without blocking, or 0 if an error occurs.

Construct a basic_datagram_socket without opening it.

explicit basic_datagram_socket(
    boost::asio::io_service & io_service);
  » more...

Construct and open a basic_datagram_socket.

basic_datagram_socket(
    boost::asio::io_service & io_service,
    const protocol_type & protocol);
  » more...

Construct a basic_datagram_socket, opening it and binding it to the given local endpoint.

basic_datagram_socket(
    boost::asio::io_service & io_service,
    const endpoint_type & endpoint);
  » more...

Construct a basic_datagram_socket on an existing native socket.

basic_datagram_socket(
    boost::asio::io_service & io_service,
    const protocol_type & protocol,
    const native_handle_type & native_socket);
  » more...

Move-construct a basic_datagram_socket from another.

basic_datagram_socket(
    basic_datagram_socket && other);
  » more...

Move-construct a basic_datagram_socket from a socket of another protocol type.

template<
    typename Protocol1,
    typename DatagramSocketService1>
basic_datagram_socket(
    basic_datagram_socket< Protocol1, DatagramSocketService1 > && other,
    typename enable_if< is_convertible< Protocol1, Protocol >::value >::type *  = 0);
  » more...

Construct a basic_datagram_socket without opening it.

basic_datagram_socket(
    boost::asio::io_service & io_service);

This constructor creates a datagram socket without opening it. The open() function must be called before data can be sent or received on the socket.

Parameters

io_service

The io_service object that the datagram socket will use to dispatch handlers for any asynchronous operations performed on the socket.

Construct and open a basic_datagram_socket.

basic_datagram_socket(
    boost::asio::io_service & io_service,
    const protocol_type & protocol);

This constructor creates and opens a datagram socket.

Parameters

io_service

The io_service object that the datagram socket will use to dispatch handlers for any asynchronous operations performed on the socket.

protocol

An object specifying protocol parameters to be used.

Exceptions

boost::system::system_error

Thrown on failure.

Construct a basic_datagram_socket, opening it and binding it to the given local endpoint.

basic_datagram_socket(
    boost::asio::io_service & io_service,
    const endpoint_type & endpoint);

This constructor creates a datagram socket and automatically opens it bound to the specified endpoint on the local machine. The protocol used is the protocol associated with the given endpoint.

Parameters

io_service

The io_service object that the datagram socket will use to dispatch handlers for any asynchronous operations performed on the socket.

endpoint

An endpoint on the local machine to which the datagram socket will be bound.

Exceptions

boost::system::system_error

Thrown on failure.

Construct a basic_datagram_socket on an existing native socket.

basic_datagram_socket(
    boost::asio::io_service & io_service,
    const protocol_type & protocol,
    const native_handle_type & native_socket);

This constructor creates a datagram socket object to hold an existing native socket.

Parameters

io_service

The io_service object that the datagram socket will use to dispatch handlers for any asynchronous operations performed on the socket.

protocol

An object specifying protocol parameters to be used.

native_socket

The new underlying socket implementation.

Exceptions

boost::system::system_error

Thrown on failure.

Move-construct a basic_datagram_socket from another.

basic_datagram_socket(
    basic_datagram_socket && other);

This constructor moves a datagram socket from one object to another.

Parameters

other

The other basic_datagram_socket object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_datagram_socket(io_service&) constructor.

Move-construct a basic_datagram_socket from a socket of another protocol type.

template<
    typename Protocol1,
    typename DatagramSocketService1>
basic_datagram_socket(
    basic_datagram_socket< Protocol1, DatagramSocketService1 > && other,
    typename enable_if< is_convertible< Protocol1, Protocol >::value >::type *  = 0);

This constructor moves a datagram socket from one object to another.

Parameters

other

The other basic_datagram_socket object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_datagram_socket(io_service&) constructor.

Bind the socket to the given local endpoint.

void bind(
    const endpoint_type & endpoint);
  » more...

boost::system::error_code bind(
    const endpoint_type & endpoint,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Bind the socket to the given local endpoint.

void bind(
    const endpoint_type & endpoint);

This function binds the socket to the specified endpoint on the local machine.

Parameters

endpoint

An endpoint on the local machine to which the socket will be bound.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::socket socket(io_service);
socket.open(boost::asio::ip::tcp::v4());
socket.bind(boost::asio::ip::tcp::endpoint(
      boost::asio::ip::tcp::v4(), 12345));

Inherited from basic_socket.

Bind the socket to the given local endpoint.

boost::system::error_code bind(
    const endpoint_type & endpoint,
    boost::system::error_code & ec);

This function binds the socket to the specified endpoint on the local machine.

Parameters

endpoint

An endpoint on the local machine to which the socket will be bound.

ec

Set to indicate what error occurred, if any.

Example
boost::asio::ip::tcp::socket socket(io_service);
socket.open(boost::asio::ip::tcp::v4());
boost::system::error_code ec;
socket.bind(boost::asio::ip::tcp::endpoint(
      boost::asio::ip::tcp::v4(), 12345), ec);
if (ec)
{
  // An error occurred.
}

Inherited from socket_base.

Socket option to permit sending of broadcast messages.

typedef implementation_defined broadcast;

Implements the SOL_SOCKET/SO_BROADCAST socket option.

Examples

Setting the option:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::broadcast option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::broadcast option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_datagram_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

IO control command to get the amount of data that can be read without blocking.

typedef implementation_defined bytes_readable;

Implements the FIONREAD IO control command.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::bytes_readable command(true);
socket.io_control(command);
std::size_t bytes_readable = command.get();
Requirements

Header: boost/asio/basic_datagram_socket.hpp

Convenience header: boost/asio.hpp

Cancel all asynchronous operations associated with the socket.

void cancel();
  » more...

boost::system::error_code cancel(
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Cancel all asynchronous operations associated with the socket.

void cancel();

This function causes all outstanding asynchronous connect, send and receive operations to finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Calls to cancel() will always fail with boost::asio::error::operation_not_supported when run on Windows XP, Windows Server 2003, and earlier versions of Windows, unless BOOST_ASIO_ENABLE_CANCELIO is defined. However, the CancelIo function has two issues that should be considered before enabling its use:

  • It will only cancel asynchronous operations that were initiated in the current thread.
  • It can appear to complete without error, but the request to cancel the unfinished operations may be silently ignored by the operating system. Whether it works or not seems to depend on the drivers that are installed.

For portable cancellation, consider using one of the following alternatives:

  • Disable asio's I/O completion port backend by defining BOOST_ASIO_DISABLE_IOCP.
  • Use the close() function to simultaneously cancel the outstanding operations and close the socket.

When running on Windows Vista, Windows Server 2008, and later, the CancelIoEx function is always used. This function does not have the problems described above.

Inherited from basic_socket.

Cancel all asynchronous operations associated with the socket.

boost::system::error_code cancel(
    boost::system::error_code & ec);

This function causes all outstanding asynchronous connect, send and receive operations to finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error.

Parameters

ec

Set to indicate what error occurred, if any.

Remarks

Calls to cancel() will always fail with boost::asio::error::operation_not_supported when run on Windows XP, Windows Server 2003, and earlier versions of Windows, unless BOOST_ASIO_ENABLE_CANCELIO is defined. However, the CancelIo function has two issues that should be considered before enabling its use:

  • It will only cancel asynchronous operations that were initiated in the current thread.
  • It can appear to complete without error, but the request to cancel the unfinished operations may be silently ignored by the operating system. Whether it works or not seems to depend on the drivers that are installed.

For portable cancellation, consider using one of the following alternatives:

  • Disable asio's I/O completion port backend by defining BOOST_ASIO_DISABLE_IOCP.
  • Use the close() function to simultaneously cancel the outstanding operations and close the socket.

When running on Windows Vista, Windows Server 2008, and later, the CancelIoEx function is always used. This function does not have the problems described above.

Close the socket.

void close();
  » more...

boost::system::error_code close(
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Close the socket.

void close();

This function is used to close the socket. Any asynchronous send, receive or connect operations will be cancelled immediately, and will complete with the boost::asio::error::operation_aborted error.

Exceptions

boost::system::system_error

Thrown on failure. Note that, even if the function indicates an error, the underlying descriptor is closed.

Remarks

For portable behaviour with respect to graceful closure of a connected socket, call shutdown() before closing the socket.

Inherited from basic_socket.

Close the socket.

boost::system::error_code close(
    boost::system::error_code & ec);

This function is used to close the socket. Any asynchronous send, receive or connect operations will be cancelled immediately, and will complete with the boost::asio::error::operation_aborted error.

Parameters

ec

Set to indicate what error occurred, if any. Note that, even if the function indicates an error, the underlying descriptor is closed.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::system::error_code ec;
socket.close(ec);
if (ec)
{
  // An error occurred.
}
Remarks

For portable behaviour with respect to graceful closure of a connected socket, call shutdown() before closing the socket.

Connect the socket to the specified endpoint.

void connect(
    const endpoint_type & peer_endpoint);
  » more...

boost::system::error_code connect(
    const endpoint_type & peer_endpoint,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Connect the socket to the specified endpoint.

void connect(
    const endpoint_type & peer_endpoint);

This function is used to connect a socket to the specified remote endpoint. The function call will block until the connection is successfully made or an error occurs.

The socket is automatically opened if it is not already open. If the connect fails, and the socket was automatically opened, the socket is not returned to the closed state.

Parameters

peer_endpoint

The remote endpoint to which the socket will be connected.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::socket socket(io_service);
boost::asio::ip::tcp::endpoint endpoint(
    boost::asio::ip::address::from_string("1.2.3.4"), 12345);
socket.connect(endpoint);

Inherited from basic_socket.

Connect the socket to the specified endpoint.

boost::system::error_code connect(
    const endpoint_type & peer_endpoint,
    boost::system::error_code & ec);

This function is used to connect a socket to the specified remote endpoint. The function call will block until the connection is successfully made or an error occurs.

The socket is automatically opened if it is not already open. If the connect fails, and the socket was automatically opened, the socket is not returned to the closed state.

Parameters

peer_endpoint

The remote endpoint to which the socket will be connected.

ec

Set to indicate what error occurred, if any.

Example
boost::asio::ip::tcp::socket socket(io_service);
boost::asio::ip::tcp::endpoint endpoint(
    boost::asio::ip::address::from_string("1.2.3.4"), 12345);
boost::system::error_code ec;
socket.connect(endpoint, ec);
if (ec)
{
  // An error occurred.
}

Inherited from socket_base.

Socket option to enable socket-level debugging.

typedef implementation_defined debug;

Implements the SOL_SOCKET/SO_DEBUG socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::debug option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::debug option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_datagram_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option to prevent routing, use local interfaces only.

typedef implementation_defined do_not_route;

Implements the SOL_SOCKET/SO_DONTROUTE socket option.

Examples

Setting the option:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::do_not_route option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::do_not_route option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_datagram_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option to report aborted connections on accept.

typedef implementation_defined enable_connection_aborted;

Implements a custom socket option that determines whether or not an accept operation is permitted to fail with boost::asio::error::connection_aborted. By default the option is false.

Examples

Setting the option:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::enable_connection_aborted option(true);
acceptor.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::enable_connection_aborted option;
acceptor.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_datagram_socket.hpp

Convenience header: boost/asio.hpp

The endpoint type.

typedef Protocol::endpoint endpoint_type;
Requirements

Header: boost/asio/basic_datagram_socket.hpp

Convenience header: boost/asio.hpp

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();
  » more...

const implementation_type & get_implementation() const;
  » more...

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

const implementation_type & get_implementation() const;

Inherited from basic_io_object.

Get the io_service associated with the object.

boost::asio::io_service & get_io_service();

This function may be used to obtain the io_service object that the I/O object uses to dispatch handlers for asynchronous operations.

Return Value

A reference to the io_service object that the I/O object will use to dispatch handlers. Ownership is not transferred to the caller.

Get an option from the socket.

void get_option(
    GettableSocketOption & option) const;
  » more...

boost::system::error_code get_option(
    GettableSocketOption & option,
    boost::system::error_code & ec) const;
  » more...

Inherited from basic_socket.

Get an option from the socket.

template<
    typename GettableSocketOption>
void get_option(
    GettableSocketOption & option) const;

This function is used to get the current value of an option on the socket.

Parameters

option

The option value to be obtained from the socket.

Exceptions

boost::system::system_error

Thrown on failure.

Example

Getting the value of the SOL_SOCKET/SO_KEEPALIVE option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::socket::keep_alive option;
socket.get_option(option);
bool is_set = option.value();

Inherited from basic_socket.

Get an option from the socket.

template<
    typename GettableSocketOption>
boost::system::error_code get_option(
    GettableSocketOption & option,
    boost::system::error_code & ec) const;

This function is used to get the current value of an option on the socket.

Parameters

option

The option value to be obtained from the socket.

ec

Set to indicate what error occurred, if any.

Example

Getting the value of the SOL_SOCKET/SO_KEEPALIVE option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::socket::keep_alive option;
boost::system::error_code ec;
socket.get_option(option, ec);
if (ec)
{
  // An error occurred.
}
bool is_set = option.value();

Get the service associated with the I/O object.

service_type & get_service();
  » more...

const service_type & get_service() const;
  » more...

Inherited from basic_io_object.

Get the service associated with the I/O object.

service_type & get_service();

Inherited from basic_io_object.

Get the service associated with the I/O object.

const service_type & get_service() const;

Inherited from basic_io_object.

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

implementation_type implementation;

Inherited from basic_io_object.

The underlying implementation type of I/O object.

typedef service_type::implementation_type implementation_type;
Requirements

Header: boost/asio/basic_datagram_socket.hpp

Convenience header: boost/asio.hpp

Perform an IO control command on the socket.

void io_control(
    IoControlCommand & command);
  » more...

boost::system::error_code io_control(
    IoControlCommand & command,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Perform an IO control command on the socket.

template<
    typename IoControlCommand>
void io_control(
    IoControlCommand & command);

This function is used to execute an IO control command on the socket.

Parameters

command

The IO control command to be performed on the socket.

Exceptions

boost::system::system_error

Thrown on failure.

Example

Getting the number of bytes ready to read:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::socket::bytes_readable command;
socket.io_control(command);
std::size_t bytes_readable = command.get();

Inherited from basic_socket.

Perform an IO control command on the socket.

template<
    typename IoControlCommand>
boost::system::error_code io_control(
    IoControlCommand & command,
    boost::system::error_code & ec);

This function is used to execute an IO control command on the socket.

Parameters

command

The IO control command to be performed on the socket.

ec

Set to indicate what error occurred, if any.

Example

Getting the number of bytes ready to read:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::socket::bytes_readable command;
boost::system::error_code ec;
socket.io_control(command, ec);
if (ec)
{
  // An error occurred.
}
std::size_t bytes_readable = command.get();

Inherited from basic_socket.

Determine whether the socket is open.

bool is_open() const;

Inherited from socket_base.

Socket option to send keep-alives.

typedef implementation_defined keep_alive;

Implements the SOL_SOCKET/SO_KEEPALIVE socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::keep_alive option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::keep_alive option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_datagram_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

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.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::linger option(true, 30);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::linger option;
socket.get_option(option);
bool is_set = option.enabled();
unsigned short timeout = option.timeout();
Requirements

Header: boost/asio/basic_datagram_socket.hpp

Convenience header: boost/asio.hpp

Get the local endpoint of the socket.

endpoint_type local_endpoint() const;
  » more...

endpoint_type local_endpoint(
    boost::system::error_code & ec) const;
  » more...

Inherited from basic_socket.

Get the local endpoint of the socket.

endpoint_type local_endpoint() const;

This function is used to obtain the locally bound endpoint of the socket.

Return Value

An object that represents the local endpoint of the socket.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::endpoint endpoint = socket.local_endpoint();

Inherited from basic_socket.

Get the local endpoint of the socket.

endpoint_type local_endpoint(
    boost::system::error_code & ec) const;

This function is used to obtain the locally bound endpoint of the socket.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

An object that represents the local endpoint of the socket. Returns a default-constructed endpoint object if an error occurred.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::system::error_code ec;
boost::asio::ip::tcp::endpoint endpoint = socket.local_endpoint(ec);
if (ec)
{
  // An error occurred.
}

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();
  » more...

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;
  » more...

Inherited from basic_socket.

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();

This function returns a reference to the lowest layer in a stack of layers. Since a basic_socket cannot contain any further layers, it simply returns a reference to itself.

Return Value

A reference to the lowest layer in the stack of layers. Ownership is not transferred to the caller.

Inherited from basic_socket.

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;

This function returns a const reference to the lowest layer in a stack of layers. Since a basic_socket cannot contain any further layers, it simply returns a reference to itself.

Return Value

A const reference to the lowest layer in the stack of layers. Ownership is not transferred to the caller.

Inherited from basic_socket.

A basic_socket is always the lowest layer.

typedef basic_socket< Protocol, DatagramSocketService > lowest_layer_type;
Types

Name

Description

broadcast

Socket option to permit sending of broadcast messages.

bytes_readable

IO control command to get the amount of data that can be read without blocking.

debug

Socket option to enable socket-level debugging.

do_not_route

Socket option to prevent routing, use local interfaces only.

enable_connection_aborted

Socket option to report aborted connections on accept.

endpoint_type

The endpoint type.

implementation_type

The underlying implementation type of I/O object.

keep_alive

Socket option to send keep-alives.

linger

Socket option to specify whether the socket lingers on close if unsent data is present.

lowest_layer_type

A basic_socket is always the lowest layer.

message_flags

Bitmask type for flags that can be passed to send and receive operations.

native_handle_type

The native representation of a socket.

native_type

(Deprecated: Use native_handle_type.) The native representation of a socket.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

protocol_type

The protocol type.

receive_buffer_size

Socket option for the receive buffer size of a socket.

receive_low_watermark

Socket option for the receive low watermark.

reuse_address

Socket option to allow the socket to be bound to an address that is already in use.

send_buffer_size

Socket option for the send buffer size of a socket.

send_low_watermark

Socket option for the send low watermark.

service_type

The type of the service that will be used to provide I/O operations.

shutdown_type

Different ways a socket may be shutdown.

Member Functions

Name

Description

assign

Assign an existing native socket to the socket.

async_connect

Start an asynchronous connect.

at_mark

Determine whether the socket is at the out-of-band data mark.

available

Determine the number of bytes available for reading.

basic_socket

Construct a basic_socket without opening it.

Construct and open a basic_socket.

Construct a basic_socket, opening it and binding it to the given local endpoint.

Construct a basic_socket on an existing native socket.

Move-construct a basic_socket from another.

Move-construct a basic_socket from a socket of another protocol type.

bind

Bind the socket to the given local endpoint.

cancel

Cancel all asynchronous operations associated with the socket.

close

Close the socket.

connect

Connect the socket to the specified endpoint.

get_io_service

Get the io_service associated with the object.

get_option

Get an option from the socket.

io_control

Perform an IO control command on the socket.

is_open

Determine whether the socket is open.

local_endpoint

Get the local endpoint of the socket.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native socket representation.

native_handle

Get the native socket representation.

native_non_blocking

Gets the non-blocking mode of the native socket implementation.

Sets the non-blocking mode of the native socket implementation.

non_blocking

Gets the non-blocking mode of the socket.

Sets the non-blocking mode of the socket.

open

Open the socket using the specified protocol.

operator=

Move-assign a basic_socket from another.

Move-assign a basic_socket from a socket of another protocol type.

remote_endpoint

Get the remote endpoint of the socket.

set_option

Set an option on the socket.

shutdown

Disable sends or receives on the socket.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

~basic_socket

Protected destructor to prevent deletion through this type.

Data Members

Name

Description

max_connections

The maximum length of the queue of pending incoming connections.

message_do_not_route

Specify that the data should not be subject to routing.

message_end_of_record

Specifies that the data marks the end of a record.

message_out_of_band

Process out-of-band data.

message_peek

Peek at incoming data without removing it from the input queue.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_socket class template provides functionality that is common to both stream-oriented and datagram-oriented sockets.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/basic_datagram_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

The maximum length of the queue of pending incoming connections.

static const int max_connections = implementation_defined;

Inherited from socket_base.

Specify that the data should not be subject to routing.

static const int message_do_not_route = implementation_defined;

Inherited from socket_base.

Specifies that the data marks the end of a record.

static const int message_end_of_record = implementation_defined;

Inherited from socket_base.

Bitmask type for flags that can be passed to send and receive operations.

typedef int message_flags;
Requirements

Header: boost/asio/basic_datagram_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Process out-of-band data.

static const int message_out_of_band = implementation_defined;

Inherited from socket_base.

Peek at incoming data without removing it from the input queue.

static const int message_peek = implementation_defined;

Inherited from basic_socket.

(Deprecated: Use native_handle().) Get the native socket representation.

native_type native();

This function may be used to obtain the underlying representation of the socket. This is intended to allow access to native socket functionality that is not otherwise provided.

Inherited from basic_socket.

Get the native socket representation.

native_handle_type native_handle();

This function may be used to obtain the underlying representation of the socket. This is intended to allow access to native socket functionality that is not otherwise provided.

The native representation of a socket.

typedef DatagramSocketService::native_handle_type native_handle_type;
Requirements

Header: boost/asio/basic_datagram_socket.hpp

Convenience header: boost/asio.hpp

Gets the non-blocking mode of the native socket implementation.

bool native_non_blocking() const;
  » more...

Sets the non-blocking mode of the native socket implementation.

void native_non_blocking(
    bool mode);
  » more...

boost::system::error_code native_non_blocking(
    bool mode,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Gets the non-blocking mode of the native socket implementation.

bool native_non_blocking() const;

This function is used to retrieve the non-blocking mode of the underlying native socket. This mode has no effect on the behaviour of the socket object's synchronous operations.

Return Value

true if the underlying socket is in non-blocking mode and direct system calls may fail with boost::asio::error::would_block (or the equivalent system error).

Remarks

The current non-blocking mode is cached by the socket object. Consequently, the return value may be incorrect if the non-blocking mode was set directly on the native socket.

Example

This function is intended to allow the encapsulation of arbitrary non-blocking system calls as asynchronous operations, in a way that is transparent to the user of the socket object. The following example illustrates how Linux's sendfile system call might be encapsulated:

template <typename Handler>
struct sendfile_op
{
  tcp::socket& sock_;
  int fd_;
  Handler handler_;
  off_t offset_;
  std::size_t total_bytes_transferred_;

  // Function call operator meeting WriteHandler requirements.
  // Used as the handler for the async_write_some operation.
  void operator()(boost::system::error_code ec, std::size_t)
  {
    // Put the underlying socket into non-blocking mode.
    if (!ec)
      if (!sock_.native_non_blocking())
        sock_.native_non_blocking(true, ec);

    if (!ec)
    {
      for (;;)
      {
        // Try the system call.
        errno = 0;
        int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536);
        ec = boost::system::error_code(n < 0 ? errno : 0,
            boost::asio::error::get_system_category());
        total_bytes_transferred_ += ec ? 0 : n;

        // Retry operation immediately if interrupted by signal.
        if (ec == boost::asio::error::interrupted)
          continue;

        // Check if we need to run the operation again.
        if (ec == boost::asio::error::would_block
            || ec == boost::asio::error::try_again)
        {
          // We have to wait for the socket to become ready again.
          sock_.async_write_some(boost::asio::null_buffers(), *this);
          return;
        }

        if (ec || n == 0)
        {
          // An error occurred, or we have reached the end of the file.
          // Either way we must exit the loop so we can call the handler.
          break;
        }

        // Loop around to try calling sendfile again.
      }
    }

    // Pass result back to user's handler.
    handler_(ec, total_bytes_transferred_);
  }
};

template <typename Handler>
void async_sendfile(tcp::socket& sock, int fd, Handler h)
{
  sendfile_op<Handler> op = { sock, fd, h, 0, 0 };
  sock.async_write_some(boost::asio::null_buffers(), op);
}

Inherited from basic_socket.

Sets the non-blocking mode of the native socket implementation.

void native_non_blocking(
    bool mode);

This function is used to modify the non-blocking mode of the underlying native socket. It has no effect on the behaviour of the socket object's synchronous operations.

Parameters

mode

If true, the underlying socket is put into non-blocking mode and direct system calls may fail with boost::asio::error::would_block (or the equivalent system error).

Exceptions

boost::system::system_error

Thrown on failure. If the mode is false, but the current value of non_blocking() is true, this function fails with boost::asio::error::invalid_argument, as the combination does not make sense.

Example

This function is intended to allow the encapsulation of arbitrary non-blocking system calls as asynchronous operations, in a way that is transparent to the user of the socket object. The following example illustrates how Linux's sendfile system call might be encapsulated:

template <typename Handler>
struct sendfile_op
{
  tcp::socket& sock_;
  int fd_;
  Handler handler_;
  off_t offset_;
  std::size_t total_bytes_transferred_;

  // Function call operator meeting WriteHandler requirements.
  // Used as the handler for the async_write_some operation.
  void operator()(boost::system::error_code ec, std::size_t)
  {
    // Put the underlying socket into non-blocking mode.
    if (!ec)
      if (!sock_.native_non_blocking())
        sock_.native_non_blocking(true, ec);

    if (!ec)
    {
      for (;;)
      {
        // Try the system call.
        errno = 0;
        int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536);
        ec = boost::system::error_code(n < 0 ? errno : 0,
            boost::asio::error::get_system_category());
        total_bytes_transferred_ += ec ? 0 : n;

        // Retry operation immediately if interrupted by signal.
        if (ec == boost::asio::error::interrupted)
          continue;

        // Check if we need to run the operation again.
        if (ec == boost::asio::error::would_block
            || ec == boost::asio::error::try_again)
        {
          // We have to wait for the socket to become ready again.
          sock_.async_write_some(boost::asio::null_buffers(), *this);
          return;
        }

        if (ec || n == 0)
        {
          // An error occurred, or we have reached the end of the file.
          // Either way we must exit the loop so we can call the handler.
          break;
        }

        // Loop around to try calling sendfile again.
      }
    }

    // Pass result back to user's handler.
    handler_(ec, total_bytes_transferred_);
  }
};

template <typename Handler>
void async_sendfile(tcp::socket& sock, int fd, Handler h)
{
  sendfile_op<Handler> op = { sock, fd, h, 0, 0 };
  sock.async_write_some(boost::asio::null_buffers(), op);
}

Inherited from basic_socket.

Sets the non-blocking mode of the native socket implementation.

boost::system::error_code native_non_blocking(
    bool mode,
    boost::system::error_code & ec);

This function is used to modify the non-blocking mode of the underlying native socket. It has no effect on the behaviour of the socket object's synchronous operations.

Parameters

mode

If true, the underlying socket is put into non-blocking mode and direct system calls may fail with boost::asio::error::would_block (or the equivalent system error).

ec

Set to indicate what error occurred, if any. If the mode is false, but the current value of non_blocking() is true, this function fails with boost::asio::error::invalid_argument, as the combination does not make sense.

Example

This function is intended to allow the encapsulation of arbitrary non-blocking system calls as asynchronous operations, in a way that is transparent to the user of the socket object. The following example illustrates how Linux's sendfile system call might be encapsulated:

template <typename Handler>
struct sendfile_op
{
  tcp::socket& sock_;
  int fd_;
  Handler handler_;
  off_t offset_;
  std::size_t total_bytes_transferred_;

  // Function call operator meeting WriteHandler requirements.
  // Used as the handler for the async_write_some operation.
  void operator()(boost::system::error_code ec, std::size_t)
  {
    // Put the underlying socket into non-blocking mode.
    if (!ec)
      if (!sock_.native_non_blocking())
        sock_.native_non_blocking(true, ec);

    if (!ec)
    {
      for (;;)
      {
        // Try the system call.
        errno = 0;
        int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536);
        ec = boost::system::error_code(n < 0 ? errno : 0,
            boost::asio::error::get_system_category());
        total_bytes_transferred_ += ec ? 0 : n;

        // Retry operation immediately if interrupted by signal.
        if (ec == boost::asio::error::interrupted)
          continue;

        // Check if we need to run the operation again.
        if (ec == boost::asio::error::would_block
            || ec == boost::asio::error::try_again)
        {
          // We have to wait for the socket to become ready again.
          sock_.async_write_some(boost::asio::null_buffers(), *this);
          return;
        }

        if (ec || n == 0)
        {
          // An error occurred, or we have reached the end of the file.
          // Either way we must exit the loop so we can call the handler.
          break;
        }

        // Loop around to try calling sendfile again.
      }
    }

    // Pass result back to user's handler.
    handler_(ec, total_bytes_transferred_);
  }
};

template <typename Handler>
void async_sendfile(tcp::socket& sock, int fd, Handler h)
{
  sendfile_op<Handler> op = { sock, fd, h, 0, 0 };
  sock.async_write_some(boost::asio::null_buffers(), op);
}

(Deprecated: Use native_handle_type.) The native representation of a socket.

typedef DatagramSocketService::native_handle_type native_type;
Requirements

Header: boost/asio/basic_datagram_socket.hpp

Convenience header: boost/asio.hpp

Gets the non-blocking mode of the socket.

bool non_blocking() const;
  » more...

Sets the non-blocking mode of the socket.

void non_blocking(
    bool mode);
  » more...

boost::system::error_code non_blocking(
    bool mode,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Gets the non-blocking mode of the socket.

bool non_blocking() const;
Return Value

true if the socket's synchronous operations will fail with boost::asio::error::would_block if they are unable to perform the requested operation immediately. If false, synchronous operations will block until complete.

Remarks

The non-blocking mode has no effect on the behaviour of asynchronous operations. Asynchronous operations will never fail with the error boost::asio::error::would_block.

Inherited from basic_socket.

Sets the non-blocking mode of the socket.

void non_blocking(
    bool mode);
Parameters

mode

If true, the socket's synchronous operations will fail with boost::asio::error::would_block if they are unable to perform the requested operation immediately. If false, synchronous operations will block until complete.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

The non-blocking mode has no effect on the behaviour of asynchronous operations. Asynchronous operations will never fail with the error boost::asio::error::would_block.

Inherited from basic_socket.

Sets the non-blocking mode of the socket.

boost::system::error_code non_blocking(
    bool mode,
    boost::system::error_code & ec);
Parameters

mode

If true, the socket's synchronous operations will fail with boost::asio::error::would_block if they are unable to perform the requested operation immediately. If false, synchronous operations will block until complete.

ec

Set to indicate what error occurred, if any.

Remarks

The non-blocking mode has no effect on the behaviour of asynchronous operations. Asynchronous operations will never fail with the error boost::asio::error::would_block.

Inherited from socket_base.

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

typedef implementation_defined non_blocking_io;

Implements the FIONBIO IO control command.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::non_blocking_io command(true);
socket.io_control(command);
Requirements

Header: boost/asio/basic_datagram_socket.hpp

Convenience header: boost/asio.hpp

Open the socket using the specified protocol.

void open(
    const protocol_type & protocol = protocol_type());
  » more...

boost::system::error_code open(
    const protocol_type & protocol,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Open the socket using the specified protocol.

void open(
    const protocol_type & protocol = protocol_type());

This function opens the socket so that it will use the specified protocol.

Parameters

protocol

An object specifying protocol parameters to be used.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::socket socket(io_service);
socket.open(boost::asio::ip::tcp::v4());

Inherited from basic_socket.

Open the socket using the specified protocol.

boost::system::error_code open(
    const protocol_type & protocol,
    boost::system::error_code & ec);

This function opens the socket so that it will use the specified protocol.

Parameters

protocol

An object specifying which protocol is to be used.

ec

Set to indicate what error occurred, if any.

Example
boost::asio::ip::tcp::socket socket(io_service);
boost::system::error_code ec;
socket.open(boost::asio::ip::tcp::v4(), ec);
if (ec)
{
  // An error occurred.
}

Move-assign a basic_datagram_socket from another.

basic_datagram_socket & operator=(
    basic_datagram_socket && other);
  » more...

Move-assign a basic_datagram_socket from a socket of another protocol type.

template<
    typename Protocol1,
    typename DatagramSocketService1>
enable_if< is_convertible< Protocol1, Protocol >::value, basic_datagram_socket >::type & operator=(
    basic_datagram_socket< Protocol1, DatagramSocketService1 > && other);
  » more...

Move-assign a basic_datagram_socket from another.

basic_datagram_socket & operator=(
    basic_datagram_socket && other);

This assignment operator moves a datagram socket from one object to another.

Parameters

other

The other basic_datagram_socket object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_datagram_socket(io_service&) constructor.

Move-assign a basic_datagram_socket from a socket of another protocol type.

template<
    typename Protocol1,
    typename DatagramSocketService1>
enable_if< is_convertible< Protocol1, Protocol >::value, basic_datagram_socket >::type & operator=(
    basic_datagram_socket< Protocol1, DatagramSocketService1 > && other);

This assignment operator moves a datagram socket from one object to another.

Parameters

other

The other basic_datagram_socket object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_datagram_socket(io_service&) constructor.

The protocol type.

typedef Protocol protocol_type;
Requirements

Header: boost/asio/basic_datagram_socket.hpp

Convenience header: boost/asio.hpp

Receive some data on a connected socket.

template<
    typename MutableBufferSequence>
std::size_t receive(
    const MutableBufferSequence & buffers);
  » more...

template<
    typename MutableBufferSequence>
std::size_t receive(
    const MutableBufferSequence & buffers,
    socket_base::message_flags flags);
  » more...

template<
    typename MutableBufferSequence>
std::size_t receive(
    const MutableBufferSequence & buffers,
    socket_base::message_flags flags,
    boost::system::error_code & ec);
  » more...

Receive some data on a connected socket.

template<
    typename MutableBufferSequence>
std::size_t receive(
    const MutableBufferSequence & buffers);

This function is used to receive data on the datagram socket. The function call will block until data has been received successfully or an error occurs.

Parameters

buffers

One or more buffers into which the data will be received.

Return Value

The number of bytes received.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

The receive operation can only be used with a connected socket. Use the receive_from function to receive data on an unconnected datagram socket.

Example

To receive into a single data buffer use the buffer function as follows:

socket.receive(boost::asio::buffer(data, size));

See the buffer documentation for information on receiving into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Receive some data on a connected socket.

template<
    typename MutableBufferSequence>
std::size_t receive(
    const MutableBufferSequence & buffers,
    socket_base::message_flags flags);

This function is used to receive data on the datagram socket. The function call will block until data has been received successfully or an error occurs.

Parameters

buffers

One or more buffers into which the data will be received.

flags

Flags specifying how the receive call is to be made.

Return Value

The number of bytes received.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

The receive operation can only be used with a connected socket. Use the receive_from function to receive data on an unconnected datagram socket.

Receive some data on a connected socket.

template<
    typename MutableBufferSequence>
std::size_t receive(
    const MutableBufferSequence & buffers,
    socket_base::message_flags flags,
    boost::system::error_code & ec);

This function is used to receive data on the datagram socket. The function call will block until data has been received successfully or an error occurs.

Parameters

buffers

One or more buffers into which the data will be received.

flags

Flags specifying how the receive call is to be made.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes received.

Remarks

The receive operation can only be used with a connected socket. Use the receive_from function to receive data on an unconnected datagram socket.

Inherited from socket_base.

Socket option for the receive buffer size of a socket.

typedef implementation_defined receive_buffer_size;

Implements the SOL_SOCKET/SO_RCVBUF socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_buffer_size option(8192);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_buffer_size option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/basic_datagram_socket.hpp

Convenience header: boost/asio.hpp

Receive a datagram with the endpoint of the sender.

template<
    typename MutableBufferSequence>
std::size_t receive_from(
    const MutableBufferSequence & buffers,
    endpoint_type & sender_endpoint);
  » more...

template<
    typename MutableBufferSequence>
std::size_t receive_from(
    const MutableBufferSequence & buffers,
    endpoint_type & sender_endpoint,
    socket_base::message_flags flags);
  » more...

template<
    typename MutableBufferSequence>
std::size_t receive_from(
    const MutableBufferSequence & buffers,
    endpoint_type & sender_endpoint,
    socket_base::message_flags flags,
    boost::system::error_code & ec);
  » more...

Receive a datagram with the endpoint of the sender.

template<
    typename MutableBufferSequence>
std::size_t receive_from(
    const MutableBufferSequence & buffers,
    endpoint_type & sender_endpoint);

This function is used to receive a datagram. The function call will block until data has been received successfully or an error occurs.

Parameters

buffers

One or more buffers into which the data will be received.

sender_endpoint

An endpoint object that receives the endpoint of the remote sender of the datagram.

Return Value

The number of bytes received.

Exceptions

boost::system::system_error

Thrown on failure.

Example

To receive into a single data buffer use the buffer function as follows:

boost::asio::ip::udp::endpoint sender_endpoint;
socket.receive_from(
    boost::asio::buffer(data, size), sender_endpoint);

See the buffer documentation for information on receiving into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Receive a datagram with the endpoint of the sender.

template<
    typename MutableBufferSequence>
std::size_t receive_from(
    const MutableBufferSequence & buffers,
    endpoint_type & sender_endpoint,
    socket_base::message_flags flags);

This function is used to receive a datagram. The function call will block until data has been received successfully or an error occurs.

Parameters

buffers

One or more buffers into which the data will be received.

sender_endpoint

An endpoint object that receives the endpoint of the remote sender of the datagram.

flags

Flags specifying how the receive call is to be made.

Return Value

The number of bytes received.

Exceptions

boost::system::system_error

Thrown on failure.

Receive a datagram with the endpoint of the sender.

template<
    typename MutableBufferSequence>
std::size_t receive_from(
    const MutableBufferSequence & buffers,
    endpoint_type & sender_endpoint,
    socket_base::message_flags flags,
    boost::system::error_code & ec);

This function is used to receive a datagram. The function call will block until data has been received successfully or an error occurs.

Parameters

buffers

One or more buffers into which the data will be received.

sender_endpoint

An endpoint object that receives the endpoint of the remote sender of the datagram.

flags

Flags specifying how the receive call is to be made.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes received.

Inherited from socket_base.

Socket option for the receive low watermark.

typedef implementation_defined receive_low_watermark;

Implements the SOL_SOCKET/SO_RCVLOWAT socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_low_watermark option(1024);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_low_watermark option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/basic_datagram_socket.hpp

Convenience header: boost/asio.hpp

Get the remote endpoint of the socket.

endpoint_type remote_endpoint() const;
  » more...

endpoint_type remote_endpoint(
    boost::system::error_code & ec) const;
  » more...

Inherited from basic_socket.

Get the remote endpoint of the socket.

endpoint_type remote_endpoint() const;

This function is used to obtain the remote endpoint of the socket.

Return Value

An object that represents the remote endpoint of the socket.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::endpoint endpoint = socket.remote_endpoint();

Inherited from basic_socket.

Get the remote endpoint of the socket.

endpoint_type remote_endpoint(
    boost::system::error_code & ec) const;

This function is used to obtain the remote endpoint of the socket.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

An object that represents the remote endpoint of the socket. Returns a default-constructed endpoint object if an error occurred.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::system::error_code ec;
boost::asio::ip::tcp::endpoint endpoint = socket.remote_endpoint(ec);
if (ec)
{
  // An error occurred.
}

Inherited from socket_base.

Socket option to allow the socket to be bound to an address that is already in use.

typedef implementation_defined reuse_address;

Implements the SOL_SOCKET/SO_REUSEADDR socket option.

Examples

Setting the option:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::reuse_address option(true);
acceptor.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::reuse_address option;
acceptor.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_datagram_socket.hpp

Convenience header: boost/asio.hpp

Send some data on a connected socket.

template<
    typename ConstBufferSequence>
std::size_t send(
    const ConstBufferSequence & buffers);
  » more...

template<
    typename ConstBufferSequence>
std::size_t send(
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags);
  » more...

template<
    typename ConstBufferSequence>
std::size_t send(
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags,
    boost::system::error_code & ec);
  » more...

Send some data on a connected socket.

template<
    typename ConstBufferSequence>
std::size_t send(
    const ConstBufferSequence & buffers);

This function is used to send data on the datagram socket. The function call will block until the data has been sent successfully or an error occurs.

Parameters

buffers

One ore more data buffers to be sent on the socket.

Return Value

The number of bytes sent.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

The send operation can only be used with a connected socket. Use the send_to function to send data on an unconnected datagram socket.

Example

To send a single data buffer use the buffer function as follows:

socket.send(boost::asio::buffer(data, size));

See the buffer documentation for information on sending multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Send some data on a connected socket.

template<
    typename ConstBufferSequence>
std::size_t send(
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags);

This function is used to send data on the datagram socket. The function call will block until the data has been sent successfully or an error occurs.

Parameters

buffers

One ore more data buffers to be sent on the socket.

flags

Flags specifying how the send call is to be made.

Return Value

The number of bytes sent.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

The send operation can only be used with a connected socket. Use the send_to function to send data on an unconnected datagram socket.

Send some data on a connected socket.

template<
    typename ConstBufferSequence>
std::size_t send(
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags,
    boost::system::error_code & ec);

This function is used to send data on the datagram socket. The function call will block until the data has been sent successfully or an error occurs.

Parameters

buffers

One or more data buffers to be sent on the socket.

flags

Flags specifying how the send call is to be made.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes sent.

Remarks

The send operation can only be used with a connected socket. Use the send_to function to send data on an unconnected datagram socket.

Inherited from socket_base.

Socket option for the send buffer size of a socket.

typedef implementation_defined send_buffer_size;

Implements the SOL_SOCKET/SO_SNDBUF socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_buffer_size option(8192);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_buffer_size option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/basic_datagram_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option for the send low watermark.

typedef implementation_defined send_low_watermark;

Implements the SOL_SOCKET/SO_SNDLOWAT socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_low_watermark option(1024);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_low_watermark option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/basic_datagram_socket.hpp

Convenience header: boost/asio.hpp

Send a datagram to the specified endpoint.

template<
    typename ConstBufferSequence>
std::size_t send_to(
    const ConstBufferSequence & buffers,
    const endpoint_type & destination);
  » more...

template<
    typename ConstBufferSequence>
std::size_t send_to(
    const ConstBufferSequence & buffers,
    const endpoint_type & destination,
    socket_base::message_flags flags);
  » more...

template<
    typename ConstBufferSequence>
std::size_t send_to(
    const ConstBufferSequence & buffers,
    const endpoint_type & destination,
    socket_base::message_flags flags,
    boost::system::error_code & ec);
  » more...

Send a datagram to the specified endpoint.

template<
    typename ConstBufferSequence>
std::size_t send_to(
    const ConstBufferSequence & buffers,
    const endpoint_type & destination);

This function is used to send a datagram to the specified remote endpoint. The function call will block until the data has been sent successfully or an error occurs.

Parameters

buffers

One or more data buffers to be sent to the remote endpoint.

destination

The remote endpoint to which the data will be sent.

Return Value

The number of bytes sent.

Exceptions

boost::system::system_error

Thrown on failure.

Example

To send a single data buffer use the buffer function as follows:

boost::asio::ip::udp::endpoint destination(
    boost::asio::ip::address::from_string("1.2.3.4"), 12345);
socket.send_to(boost::asio::buffer(data, size), destination);

See the buffer documentation for information on sending multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Send a datagram to the specified endpoint.

template<
    typename ConstBufferSequence>
std::size_t send_to(
    const ConstBufferSequence & buffers,
    const endpoint_type & destination,
    socket_base::message_flags flags);

This function is used to send a datagram to the specified remote endpoint. The function call will block until the data has been sent successfully or an error occurs.

Parameters

buffers

One or more data buffers to be sent to the remote endpoint.

destination

The remote endpoint to which the data will be sent.

flags

Flags specifying how the send call is to be made.

Return Value

The number of bytes sent.

Exceptions

boost::system::system_error

Thrown on failure.

Send a datagram to the specified endpoint.

template<
    typename ConstBufferSequence>
std::size_t send_to(
    const ConstBufferSequence & buffers,
    const endpoint_type & destination,
    socket_base::message_flags flags,
    boost::system::error_code & ec);

This function is used to send a datagram to the specified remote endpoint. The function call will block until the data has been sent successfully or an error occurs.

Parameters

buffers

One or more data buffers to be sent to the remote endpoint.

destination

The remote endpoint to which the data will be sent.

flags

Flags specifying how the send call is to be made.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes sent.

Inherited from basic_io_object.

(Deprecated: Use get_service().) The service associated with the I/O object.

service_type & service;
Remarks

Available only for services that do not support movability.

Inherited from basic_io_object.

The type of the service that will be used to provide I/O operations.

typedef DatagramSocketService service_type;
Requirements

Header: boost/asio/basic_datagram_socket.hpp

Convenience header: boost/asio.hpp

Set an option on the socket.

void set_option(
    const SettableSocketOption & option);
  » more...

boost::system::error_code set_option(
    const SettableSocketOption & option,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

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.

Parameters

option

The new option value to be set on the socket.

Exceptions

boost::system::system_error

Thrown on failure.

Example

Setting the IPPROTO_TCP/TCP_NODELAY option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::no_delay option(true);
socket.set_option(option);

Inherited from basic_socket.

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.

Parameters

option

The new option value to be set on the socket.

ec

Set to indicate what error occurred, if any.

Example

Setting the IPPROTO_TCP/TCP_NODELAY option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::no_delay option(true);
boost::system::error_code ec;
socket.set_option(option, ec);
if (ec)
{
  // An error occurred.
}

Disable sends or receives on the socket.

void shutdown(
    shutdown_type what);
  » more...

boost::system::error_code shutdown(
    shutdown_type what,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Disable sends or receives on the socket.

void shutdown(
    shutdown_type what);

This function is used to disable send operations, receive operations, or both.

Parameters

what

Determines what types of operation will no longer be allowed.

Exceptions

boost::system::system_error

Thrown on failure.

Example

Shutting down the send side of the socket:

boost::asio::ip::tcp::socket socket(io_service);
...
socket.shutdown(boost::asio::ip::tcp::socket::shutdown_send);

Inherited from basic_socket.

Disable sends or receives on the socket.

boost::system::error_code shutdown(
    shutdown_type what,
    boost::system::error_code & ec);

This function is used to disable send operations, receive operations, or both.

Parameters

what

Determines what types of operation will no longer be allowed.

ec

Set to indicate what error occurred, if any.

Example

Shutting down the send side of the socket:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::system::error_code ec;
socket.shutdown(boost::asio::ip::tcp::socket::shutdown_send, ec);
if (ec)
{
  // An error occurred.
}

Inherited from socket_base.

Different ways a socket may be shutdown.

enum shutdown_type

Values

shutdown_receive

Shutdown the receive side of the socket.

shutdown_send

Shutdown the send side of the socket.

shutdown_both

Shutdown both send and receive on the socket.

Provides waitable timer functionality.

template<
    typename Time,
    typename TimeTraits = boost::asio::time_traits<Time>,
    typename TimerService = deadline_timer_service<Time, TimeTraits>>
class basic_deadline_timer :
  public basic_io_object< TimerService >
Types

Name

Description

duration_type

The duration type.

implementation_type

The underlying implementation type of I/O object.

service_type

The type of the service that will be used to provide I/O operations.

time_type

The time type.

traits_type

The time traits type.

Member Functions

Name

Description

async_wait

Start an asynchronous wait on the timer.

basic_deadline_timer

Constructor.

Constructor to set a particular expiry time as an absolute time.

Constructor to set a particular expiry time relative to now.

cancel

Cancel any asynchronous operations that are waiting on the timer.

cancel_one

Cancels one asynchronous operation that is waiting on the timer.

expires_at

Get the timer's expiry time as an absolute time.

Set the timer's expiry time as an absolute time.

expires_from_now

Get the timer's expiry time relative to now.

Set the timer's expiry time relative to now.

get_io_service

Get the io_service associated with the object.

wait

Perform a blocking wait on the timer.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_deadline_timer class template provides the ability to perform a blocking or asynchronous wait for a timer to expire.

A deadline timer is always in one of two states: "expired" or "not expired". If the wait() or async_wait() function is called on an expired timer, the wait operation will complete immediately.

Most applications will use the deadline_timer typedef.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Examples

Performing a blocking wait:

// Construct a timer without setting an expiry time.
boost::asio::deadline_timer timer(io_service);

// Set an expiry time relative to now.
timer.expires_from_now(boost::posix_time::seconds(5));

// Wait for the timer to expire.
timer.wait();

Performing an asynchronous wait:

void handler(const boost::system::error_code& error)
{
  if (!error)
  {
    // Timer expired.
  }
}

...

// Construct a timer with an absolute expiry time.
boost::asio::deadline_timer timer(io_service,
    boost::posix_time::time_from_string("2005-12-07 23:59:59.000"));

// Start an asynchronous wait.
timer.async_wait(handler);
Changing an active deadline_timer's expiry time

Changing the expiry time of a timer while there are pending asynchronous waits causes those wait operations to be cancelled. To ensure that the action associated with the timer is performed only once, use something like this: used:

void on_some_event()
{
  if (my_timer.expires_from_now(seconds(5)) > 0)
  {
    // We managed to cancel the timer. Start new asynchronous wait.
    my_timer.async_wait(on_timeout);
  }
  else
  {
    // Too late, timer has already expired!
  }
}

void on_timeout(const boost::system::error_code& e)
{
  if (e != boost::asio::error::operation_aborted)
  {
    // Timer was not cancelled, take necessary action.
  }
}
  • The boost::asio::basic_deadline_timer::expires_from_now() function cancels any pending asynchronous waits, and returns the number of asynchronous waits that were cancelled. If it returns 0 then you were too late and the wait handler has already been executed, or will soon be executed. If it returns 1 then the wait handler was successfully cancelled.
  • If a wait handler is cancelled, the boost::system::error_code passed to it contains the value boost::asio::error::operation_aborted.
Requirements

Header: boost/asio/basic_deadline_timer.hpp

Convenience header: boost/asio.hpp

Start an asynchronous wait on the timer.

template<
    typename WaitHandler>
void-or-deduced async_wait(
    WaitHandler handler);

This function may be used to initiate an asynchronous wait against the timer. It always returns immediately.

For each call to async_wait(), the supplied handler will be called exactly once. The handler will be called when:

  • The timer has expired.
  • The timer was cancelled, in which case the handler is passed the error code boost::asio::error::operation_aborted.
Parameters

handler

The handler to be called when the timer expires. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error // Result of operation.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Constructor.

explicit basic_deadline_timer(
    boost::asio::io_service & io_service);
  » more...

Constructor to set a particular expiry time as an absolute time.

basic_deadline_timer(
    boost::asio::io_service & io_service,
    const time_type & expiry_time);
  » more...

Constructor to set a particular expiry time relative to now.

basic_deadline_timer(
    boost::asio::io_service & io_service,
    const duration_type & expiry_time);
  » more...

Constructor.

basic_deadline_timer(
    boost::asio::io_service & io_service);

This constructor creates a timer without setting an expiry time. The expires_at() or expires_from_now() functions must be called to set an expiry time before the timer can be waited on.

Parameters

io_service

The io_service object that the timer will use to dispatch handlers for any asynchronous operations performed on the timer.

Constructor to set a particular expiry time as an absolute time.

basic_deadline_timer(
    boost::asio::io_service & io_service,
    const time_type & expiry_time);

This constructor creates a timer and sets the expiry time.

Parameters

io_service

The io_service object that the timer will use to dispatch handlers for any asynchronous operations performed on the timer.

expiry_time

The expiry time to be used for the timer, expressed as an absolute time.

Constructor to set a particular expiry time relative to now.

basic_deadline_timer(
    boost::asio::io_service & io_service,
    const duration_type & expiry_time);

This constructor creates a timer and sets the expiry time.

Parameters

io_service

The io_service object that the timer will use to dispatch handlers for any asynchronous operations performed on the timer.

expiry_time

The expiry time to be used for the timer, relative to now.

Cancel any asynchronous operations that are waiting on the timer.

std::size_t cancel();
  » more...

std::size_t cancel(
    boost::system::error_code & ec);
  » more...

Cancel any asynchronous operations that are waiting on the timer.

std::size_t cancel();

This function forces the completion of any pending asynchronous wait operations against the timer. The handler for each cancelled operation will be invoked with the boost::asio::error::operation_aborted error code.

Cancelling the timer does not change the expiry time.

Return Value

The number of asynchronous operations that were cancelled.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

If the timer has already expired when cancel() is called, then the handlers for asynchronous wait operations will:

  • have already been invoked; or
  • have been queued for invocation in the near future.

These handlers can no longer be cancelled, and therefore are passed an error code that indicates the successful completion of the wait operation.

Cancel any asynchronous operations that are waiting on the timer.

std::size_t cancel(
    boost::system::error_code & ec);

This function forces the completion of any pending asynchronous wait operations against the timer. The handler for each cancelled operation will be invoked with the boost::asio::error::operation_aborted error code.

Cancelling the timer does not change the expiry time.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

The number of asynchronous operations that were cancelled.

Remarks

If the timer has already expired when cancel() is called, then the handlers for asynchronous wait operations will:

  • have already been invoked; or
  • have been queued for invocation in the near future.

These handlers can no longer be cancelled, and therefore are passed an error code that indicates the successful completion of the wait operation.

Cancels one asynchronous operation that is waiting on the timer.

std::size_t cancel_one();
  » more...

std::size_t cancel_one(
    boost::system::error_code & ec);
  » more...

Cancels one asynchronous operation that is waiting on the timer.

std::size_t cancel_one();

This function forces the completion of one pending asynchronous wait operation against the timer. Handlers are cancelled in FIFO order. The handler for the cancelled operation will be invoked with the boost::asio::error::operation_aborted error code.

Cancelling the timer does not change the expiry time.

Return Value

The number of asynchronous operations that were cancelled. That is, either 0 or 1.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

If the timer has already expired when cancel_one() is called, then the handlers for asynchronous wait operations will:

  • have already been invoked; or
  • have been queued for invocation in the near future.

These handlers can no longer be cancelled, and therefore are passed an error code that indicates the successful completion of the wait operation.

Cancels one asynchronous operation that is waiting on the timer.

std::size_t cancel_one(
    boost::system::error_code & ec);

This function forces the completion of one pending asynchronous wait operation against the timer. Handlers are cancelled in FIFO order. The handler for the cancelled operation will be invoked with the boost::asio::error::operation_aborted error code.

Cancelling the timer does not change the expiry time.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

The number of asynchronous operations that were cancelled. That is, either 0 or 1.

Remarks

If the timer has already expired when cancel_one() is called, then the handlers for asynchronous wait operations will:

  • have already been invoked; or
  • have been queued for invocation in the near future.

These handlers can no longer be cancelled, and therefore are passed an error code that indicates the successful completion of the wait operation.

The duration type.

typedef traits_type::duration_type duration_type;
Requirements

Header: boost/asio/basic_deadline_timer.hpp

Convenience header: boost/asio.hpp

Get the timer's expiry time as an absolute time.

time_type expires_at() const;
  » more...

Set the timer's expiry time as an absolute time.

std::size_t expires_at(
    const time_type & expiry_time);
  » more...

std::size_t expires_at(
    const time_type & expiry_time,
    boost::system::error_code & ec);
  » more...

Get the timer's expiry time as an absolute time.

time_type expires_at() const;

This function may be used to obtain the timer's current expiry time. Whether the timer has expired or not does not affect this value.

Set the timer's expiry time as an absolute time.

std::size_t expires_at(
    const time_type & expiry_time);

This function sets the expiry time. Any pending asynchronous wait operations will be cancelled. The handler for each cancelled operation will be invoked with the boost::asio::error::operation_aborted error code.

Parameters

expiry_time

The expiry time to be used for the timer.

Return Value

The number of asynchronous operations that were cancelled.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

If the timer has already expired when expires_at() is called, then the handlers for asynchronous wait operations will:

  • have already been invoked; or
  • have been queued for invocation in the near future.

These handlers can no longer be cancelled, and therefore are passed an error code that indicates the successful completion of the wait operation.

Set the timer's expiry time as an absolute time.

std::size_t expires_at(
    const time_type & expiry_time,
    boost::system::error_code & ec);

This function sets the expiry time. Any pending asynchronous wait operations will be cancelled. The handler for each cancelled operation will be invoked with the boost::asio::error::operation_aborted error code.

Parameters

expiry_time

The expiry time to be used for the timer.

ec

Set to indicate what error occurred, if any.

Return Value

The number of asynchronous operations that were cancelled.

Remarks

If the timer has already expired when expires_at() is called, then the handlers for asynchronous wait operations will:

  • have already been invoked; or
  • have been queued for invocation in the near future.

These handlers can no longer be cancelled, and therefore are passed an error code that indicates the successful completion of the wait operation.

Get the timer's expiry time relative to now.

duration_type expires_from_now() const;
  » more...

Set the timer's expiry time relative to now.

std::size_t expires_from_now(
    const duration_type & expiry_time);
  » more...

std::size_t expires_from_now(
    const duration_type & expiry_time,
    boost::system::error_code & ec);
  » more...

Get the timer's expiry time relative to now.

duration_type expires_from_now() const;

This function may be used to obtain the timer's current expiry time. Whether the timer has expired or not does not affect this value.

Set the timer's expiry time relative to now.

std::size_t expires_from_now(
    const duration_type & expiry_time);

This function sets the expiry time. Any pending asynchronous wait operations will be cancelled. The handler for each cancelled operation will be invoked with the boost::asio::error::operation_aborted error code.

Parameters

expiry_time

The expiry time to be used for the timer.

Return Value

The number of asynchronous operations that were cancelled.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

If the timer has already expired when expires_from_now() is called, then the handlers for asynchronous wait operations will:

  • have already been invoked; or
  • have been queued for invocation in the near future.

These handlers can no longer be cancelled, and therefore are passed an error code that indicates the successful completion of the wait operation.

Set the timer's expiry time relative to now.

std::size_t expires_from_now(
    const duration_type & expiry_time,
    boost::system::error_code & ec);

This function sets the expiry time. Any pending asynchronous wait operations will be cancelled. The handler for each cancelled operation will be invoked with the boost::asio::error::operation_aborted error code.

Parameters

expiry_time

The expiry time to be used for the timer.

ec

Set to indicate what error occurred, if any.

Return Value

The number of asynchronous operations that were cancelled.

Remarks

If the timer has already expired when expires_from_now() is called, then the handlers for asynchronous wait operations will:

  • have already been invoked; or
  • have been queued for invocation in the near future.

These handlers can no longer be cancelled, and therefore are passed an error code that indicates the successful completion of the wait operation.

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();
  » more...

const implementation_type & get_implementation() const;
  » more...

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

const implementation_type & get_implementation() const;

Inherited from basic_io_object.

Get the io_service associated with the object.

boost::asio::io_service & get_io_service();

This function may be used to obtain the io_service object that the I/O object uses to dispatch handlers for asynchronous operations.

Return Value

A reference to the io_service object that the I/O object will use to dispatch handlers. Ownership is not transferred to the caller.

Get the service associated with the I/O object.

service_type & get_service();
  » more...

const service_type & get_service() const;
  » more...

Inherited from basic_io_object.

Get the service associated with the I/O object.

service_type & get_service();

Inherited from basic_io_object.

Get the service associated with the I/O object.

const service_type & get_service() const;

Inherited from basic_io_object.

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

implementation_type implementation;

Inherited from basic_io_object.

The underlying implementation type of I/O object.

typedef service_type::implementation_type implementation_type;
Requirements

Header: boost/asio/basic_deadline_timer.hpp

Convenience header: boost/asio.hpp

Inherited from basic_io_object.

(Deprecated: Use get_service().) The service associated with the I/O object.

service_type & service;
Remarks

Available only for services that do not support movability.

Inherited from basic_io_object.

The type of the service that will be used to provide I/O operations.

typedef TimerService service_type;
Requirements

Header: boost/asio/basic_deadline_timer.hpp

Convenience header: boost/asio.hpp

The time type.

typedef traits_type::time_type time_type;
Requirements

Header: boost/asio/basic_deadline_timer.hpp

Convenience header: boost/asio.hpp

The time traits type.

typedef TimeTraits traits_type;
Requirements

Header: boost/asio/basic_deadline_timer.hpp

Convenience header: boost/asio.hpp

Perform a blocking wait on the timer.

void wait();
  » more...

void wait(
    boost::system::error_code & ec);
  » more...

Perform a blocking wait on the timer.

void wait();

This function is used to wait for the timer to expire. This function blocks and does not return until the timer has expired.

Exceptions

boost::system::system_error

Thrown on failure.

Perform a blocking wait on the timer.

void wait(
    boost::system::error_code & ec);

This function is used to wait for the timer to expire. This function blocks and does not return until the timer has expired.

Parameters

ec

Set to indicate what error occurred, if any.

Base class for all I/O objects.

template<
    typename IoObjectService>
class basic_io_object
Types

Name

Description

implementation_type

The underlying implementation type of I/O object.

service_type

The type of the service that will be used to provide I/O operations.

Member Functions

Name

Description

get_io_service

Get the io_service associated with the object.

Protected Member Functions

Name

Description

basic_io_object

Construct a basic_io_object.

Move-construct a basic_io_object.

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

operator=

Move-assign a basic_io_object.

~basic_io_object

Protected destructor to prevent deletion through this type.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

Remarks

All I/O objects are non-copyable. However, when using C++0x, certain I/O objects do support move construction and move assignment.

Requirements

Header: boost/asio/basic_io_object.hpp

Convenience header: boost/asio.hpp

Construct a basic_io_object.

explicit basic_io_object(
    boost::asio::io_service & io_service);
  » more...

Move-construct a basic_io_object.

basic_io_object(
    basic_io_object && other);
  » more...

Construct a basic_io_object.

basic_io_object(
    boost::asio::io_service & io_service);

Performs:

get_service().construct(get_implementation());

Move-construct a basic_io_object.

basic_io_object(
    basic_io_object && other);

Performs:

get_service().move_construct(
    get_implementation(), other.get_implementation());
Remarks

Available only for services that support movability,

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();
  » more...

const implementation_type & get_implementation() const;
  » more...

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();

Get the underlying implementation of the I/O object.

const implementation_type & get_implementation() const;

Get the io_service associated with the object.

boost::asio::io_service & get_io_service();

This function may be used to obtain the io_service object that the I/O object uses to dispatch handlers for asynchronous operations.

Return Value

A reference to the io_service object that the I/O object will use to dispatch handlers. Ownership is not transferred to the caller.

Get the service associated with the I/O object.

service_type & get_service();
  » more...

const service_type & get_service() const;
  » more...

Get the service associated with the I/O object.

service_type & get_service();

Get the service associated with the I/O object.

const service_type & get_service() const;

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

implementation_type implementation;

The underlying implementation type of I/O object.

typedef service_type::implementation_type implementation_type;
Requirements

Header: boost/asio/basic_io_object.hpp

Convenience header: boost/asio.hpp

Move-assign a basic_io_object.

basic_io_object & operator=(
    basic_io_object && other);

Performs:

get_service().move_assign(get_implementation(),
    other.get_service(), other.get_implementation());
Remarks

Available only for services that support movability,

(Deprecated: Use get_service().) The service associated with the I/O object.

service_type & service;
Remarks

Available only for services that do not support movability.

The type of the service that will be used to provide I/O operations.

typedef IoObjectService service_type;
Requirements

Header: boost/asio/basic_io_object.hpp

Convenience header: boost/asio.hpp

Protected destructor to prevent deletion through this type.

~basic_io_object();

Performs:

get_service().destroy(get_implementation());
basic_raw_socket::assign
basic_raw_socket::async_connect
basic_raw_socket::async_receive
basic_raw_socket::async_receive_from
basic_raw_socket::async_send
basic_raw_socket::async_send_to
basic_raw_socket::at_mark
basic_raw_socket::available
basic_raw_socket::basic_raw_socket
basic_raw_socket::bind
basic_raw_socket::broadcast
basic_raw_socket::bytes_readable
basic_raw_socket::cancel
basic_raw_socket::close
basic_raw_socket::connect
basic_raw_socket::debug
basic_raw_socket::do_not_route
basic_raw_socket::enable_connection_aborted
basic_raw_socket::endpoint_type
basic_raw_socket::get_implementation
basic_raw_socket::get_io_service
basic_raw_socket::get_option
basic_raw_socket::get_service
basic_raw_socket::implementation
basic_raw_socket::implementation_type
basic_raw_socket::io_control
basic_raw_socket::is_open
basic_raw_socket::keep_alive
basic_raw_socket::linger
basic_raw_socket::local_endpoint
basic_raw_socket::lowest_layer
basic_raw_socket::lowest_layer_type
basic_raw_socket::max_connections
basic_raw_socket::message_do_not_route
basic_raw_socket::message_end_of_record
basic_raw_socket::message_flags
basic_raw_socket::message_out_of_band
basic_raw_socket::message_peek
basic_raw_socket::native
basic_raw_socket::native_handle
basic_raw_socket::native_handle_type
basic_raw_socket::native_non_blocking
basic_raw_socket::native_type
basic_raw_socket::non_blocking
basic_raw_socket::non_blocking_io
basic_raw_socket::open
basic_raw_socket::operator=
basic_raw_socket::protocol_type
basic_raw_socket::receive
basic_raw_socket::receive_buffer_size
basic_raw_socket::receive_from
basic_raw_socket::receive_low_watermark
basic_raw_socket::remote_endpoint
basic_raw_socket::reuse_address
basic_raw_socket::send
basic_raw_socket::send_buffer_size
basic_raw_socket::send_low_watermark
basic_raw_socket::send_to
basic_raw_socket::service
basic_raw_socket::service_type
basic_raw_socket::set_option
basic_raw_socket::shutdown
basic_raw_socket::shutdown_type

Provides raw-oriented socket functionality.

template<
    typename Protocol,
    typename RawSocketService = raw_socket_service<Protocol>>
class basic_raw_socket :
  public basic_socket< Protocol, RawSocketService >
Types

Name

Description

broadcast

Socket option to permit sending of broadcast messages.

bytes_readable

IO control command to get the amount of data that can be read without blocking.

debug

Socket option to enable socket-level debugging.

do_not_route

Socket option to prevent routing, use local interfaces only.

enable_connection_aborted

Socket option to report aborted connections on accept.

endpoint_type

The endpoint type.

implementation_type

The underlying implementation type of I/O object.

keep_alive

Socket option to send keep-alives.

linger

Socket option to specify whether the socket lingers on close if unsent data is present.

lowest_layer_type

A basic_socket is always the lowest layer.

message_flags

Bitmask type for flags that can be passed to send and receive operations.

native_handle_type

The native representation of a socket.

native_type

(Deprecated: Use native_handle_type.) The native representation of a socket.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

protocol_type

The protocol type.

receive_buffer_size

Socket option for the receive buffer size of a socket.

receive_low_watermark

Socket option for the receive low watermark.

reuse_address

Socket option to allow the socket to be bound to an address that is already in use.

send_buffer_size

Socket option for the send buffer size of a socket.

send_low_watermark

Socket option for the send low watermark.

service_type

The type of the service that will be used to provide I/O operations.

shutdown_type

Different ways a socket may be shutdown.

Member Functions

Name

Description

assign

Assign an existing native socket to the socket.

async_connect

Start an asynchronous connect.

async_receive

Start an asynchronous receive on a connected socket.

async_receive_from

Start an asynchronous receive.

async_send

Start an asynchronous send on a connected socket.

async_send_to

Start an asynchronous send.

at_mark

Determine whether the socket is at the out-of-band data mark.

available

Determine the number of bytes available for reading.

basic_raw_socket

Construct a basic_raw_socket without opening it.

Construct and open a basic_raw_socket.

Construct a basic_raw_socket, opening it and binding it to the given local endpoint.

Construct a basic_raw_socket on an existing native socket.

Move-construct a basic_raw_socket from another.

Move-construct a basic_raw_socket from a socket of another protocol type.

bind

Bind the socket to the given local endpoint.

cancel

Cancel all asynchronous operations associated with the socket.

close

Close the socket.

connect

Connect the socket to the specified endpoint.

get_io_service

Get the io_service associated with the object.

get_option

Get an option from the socket.

io_control

Perform an IO control command on the socket.

is_open

Determine whether the socket is open.

local_endpoint

Get the local endpoint of the socket.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native socket representation.

native_handle

Get the native socket representation.

native_non_blocking

Gets the non-blocking mode of the native socket implementation.

Sets the non-blocking mode of the native socket implementation.

non_blocking

Gets the non-blocking mode of the socket.

Sets the non-blocking mode of the socket.

open

Open the socket using the specified protocol.

operator=

Move-assign a basic_raw_socket from another.

Move-assign a basic_raw_socket from a socket of another protocol type.

receive

Receive some data on a connected socket.

receive_from

Receive raw data with the endpoint of the sender.

remote_endpoint

Get the remote endpoint of the socket.

send

Send some data on a connected socket.

send_to

Send raw data to the specified endpoint.

set_option

Set an option on the socket.

shutdown

Disable sends or receives on the socket.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Data Members

Name

Description

max_connections

The maximum length of the queue of pending incoming connections.

message_do_not_route

Specify that the data should not be subject to routing.

message_end_of_record

Specifies that the data marks the end of a record.

message_out_of_band

Process out-of-band data.

message_peek

Peek at incoming data without removing it from the input queue.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_raw_socket class template provides asynchronous and blocking raw-oriented socket functionality.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/basic_raw_socket.hpp

Convenience header: boost/asio.hpp

Assign an existing native socket to the socket.

void assign(
    const protocol_type & protocol,
    const native_handle_type & native_socket);
  » more...

boost::system::error_code assign(
    const protocol_type & protocol,
    const native_handle_type & native_socket,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Assign an existing native socket to the socket.

void assign(
    const protocol_type & protocol,
    const native_handle_type & native_socket);

Inherited from basic_socket.

Assign an existing native socket to the socket.

boost::system::error_code assign(
    const protocol_type & protocol,
    const native_handle_type & native_socket,
    boost::system::error_code & ec);

Inherited from basic_socket.

Start an asynchronous connect.

template<
    typename ConnectHandler>
void-or-deduced async_connect(
    const endpoint_type & peer_endpoint,
    ConnectHandler handler);

This function is used to asynchronously connect a socket to the specified remote endpoint. The function call always returns immediately.

The socket is automatically opened if it is not already open. If the connect fails, and the socket was automatically opened, the socket is not returned to the closed state.

Parameters

peer_endpoint

The remote endpoint to which the socket will be connected. Copies will be made of the endpoint object as required.

handler

The handler to be called when the connection operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error // Result of operation
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Example
void connect_handler(const boost::system::error_code& error)
{
  if (!error)
  {
    // Connect succeeded.
  }
}

...

boost::asio::ip::tcp::socket socket(io_service);
boost::asio::ip::tcp::endpoint endpoint(
    boost::asio::ip::address::from_string("1.2.3.4"), 12345);
socket.async_connect(endpoint, connect_handler);

Start an asynchronous receive on a connected socket.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_receive(
    const MutableBufferSequence & buffers,
    ReadHandler handler);
  » more...

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_receive(
    const MutableBufferSequence & buffers,
    socket_base::message_flags flags,
    ReadHandler handler);
  » more...

Start an asynchronous receive on a connected socket.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_receive(
    const MutableBufferSequence & buffers,
    ReadHandler handler);

This function is used to asynchronously receive data from the raw socket. The function call always returns immediately.

Parameters

buffers

One or more buffers into which the data will be received. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

handler

The handler to be called when the receive operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes received.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

The async_receive operation can only be used with a connected socket. Use the async_receive_from function to receive data on an unconnected raw socket.

Example

To receive into a single data buffer use the buffer function as follows:

socket.async_receive(boost::asio::buffer(data, size), handler);

See the buffer documentation for information on receiving into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Start an asynchronous receive on a connected socket.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_receive(
    const MutableBufferSequence & buffers,
    socket_base::message_flags flags,
    ReadHandler handler);

This function is used to asynchronously receive data from the raw socket. The function call always returns immediately.

Parameters

buffers

One or more buffers into which the data will be received. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

flags

Flags specifying how the receive call is to be made.

handler

The handler to be called when the receive operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes received.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

The async_receive operation can only be used with a connected socket. Use the async_receive_from function to receive data on an unconnected raw socket.

Start an asynchronous receive.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_receive_from(
    const MutableBufferSequence & buffers,
    endpoint_type & sender_endpoint,
    ReadHandler handler);
  » more...

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_receive_from(
    const MutableBufferSequence & buffers,
    endpoint_type & sender_endpoint,
    socket_base::message_flags flags,
    ReadHandler handler);
  » more...

Start an asynchronous receive.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_receive_from(
    const MutableBufferSequence & buffers,
    endpoint_type & sender_endpoint,
    ReadHandler handler);

This function is used to asynchronously receive raw data. The function call always returns immediately.

Parameters

buffers

One or more buffers into which the data will be received. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

sender_endpoint

An endpoint object that receives the endpoint of the remote sender of the data. Ownership of the sender_endpoint object is retained by the caller, which must guarantee that it is valid until the handler is called.

handler

The handler to be called when the receive operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes received.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Example

To receive into a single data buffer use the buffer function as follows:

socket.async_receive_from(
    boost::asio::buffer(data, size), 0, sender_endpoint, handler);

See the buffer documentation for information on receiving into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Start an asynchronous receive.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_receive_from(
    const MutableBufferSequence & buffers,
    endpoint_type & sender_endpoint,
    socket_base::message_flags flags,
    ReadHandler handler);

This function is used to asynchronously receive raw data. The function call always returns immediately.

Parameters

buffers

One or more buffers into which the data will be received. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

sender_endpoint

An endpoint object that receives the endpoint of the remote sender of the data. Ownership of the sender_endpoint object is retained by the caller, which must guarantee that it is valid until the handler is called.

flags

Flags specifying how the receive call is to be made.

handler

The handler to be called when the receive operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes received.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Start an asynchronous send on a connected socket.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_send(
    const ConstBufferSequence & buffers,
    WriteHandler handler);
  » more...

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_send(
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags,
    WriteHandler handler);
  » more...

Start an asynchronous send on a connected socket.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_send(
    const ConstBufferSequence & buffers,
    WriteHandler handler);

This function is used to send data on the raw socket. The function call will block until the data has been sent successfully or an error occurs.

Parameters

buffers

One or more data buffers to be sent on the socket. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

handler

The handler to be called when the send operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes sent.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

The async_send operation can only be used with a connected socket. Use the async_send_to function to send data on an unconnected raw socket.

Example

To send a single data buffer use the buffer function as follows:

socket.async_send(boost::asio::buffer(data, size), handler);

See the buffer documentation for information on sending multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Start an asynchronous send on a connected socket.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_send(
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags,
    WriteHandler handler);

This function is used to send data on the raw socket. The function call will block until the data has been sent successfully or an error occurs.

Parameters

buffers

One or more data buffers to be sent on the socket. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

flags

Flags specifying how the send call is to be made.

handler

The handler to be called when the send operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes sent.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

The async_send operation can only be used with a connected socket. Use the async_send_to function to send data on an unconnected raw socket.

Start an asynchronous send.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_send_to(
    const ConstBufferSequence & buffers,
    const endpoint_type & destination,
    WriteHandler handler);
  » more...

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_send_to(
    const ConstBufferSequence & buffers,
    const endpoint_type & destination,
    socket_base::message_flags flags,
    WriteHandler handler);
  » more...

Start an asynchronous send.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_send_to(
    const ConstBufferSequence & buffers,
    const endpoint_type & destination,
    WriteHandler handler);

This function is used to asynchronously send raw data to the specified remote endpoint. The function call always returns immediately.

Parameters

buffers

One or more data buffers to be sent to the remote endpoint. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

destination

The remote endpoint to which the data will be sent. Copies will be made of the endpoint as required.

handler

The handler to be called when the send operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes sent.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Example

To send a single data buffer use the buffer function as follows:

boost::asio::ip::udp::endpoint destination(
    boost::asio::ip::address::from_string("1.2.3.4"), 12345);
socket.async_send_to(
    boost::asio::buffer(data, size), destination, handler);

See the buffer documentation for information on sending multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Start an asynchronous send.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_send_to(
    const ConstBufferSequence & buffers,
    const endpoint_type & destination,
    socket_base::message_flags flags,
    WriteHandler handler);

This function is used to asynchronously send raw data to the specified remote endpoint. The function call always returns immediately.

Parameters

buffers

One or more data buffers to be sent to the remote endpoint. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

flags

Flags specifying how the send call is to be made.

destination

The remote endpoint to which the data will be sent. Copies will be made of the endpoint as required.

handler

The handler to be called when the send operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes sent.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Determine whether the socket is at the out-of-band data mark.

bool at_mark() const;
  » more...

bool at_mark(
    boost::system::error_code & ec) const;
  » more...

Inherited from basic_socket.

Determine whether the socket is at the out-of-band data mark.

bool at_mark() const;

This function is used to check whether the socket input is currently positioned at the out-of-band data mark.

Return Value

A bool indicating whether the socket is at the out-of-band data mark.

Exceptions

boost::system::system_error

Thrown on failure.

Inherited from basic_socket.

Determine whether the socket is at the out-of-band data mark.

bool at_mark(
    boost::system::error_code & ec) const;

This function is used to check whether the socket input is currently positioned at the out-of-band data mark.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

A bool indicating whether the socket is at the out-of-band data mark.

Determine the number of bytes available for reading.

std::size_t available() const;
  » more...

std::size_t available(
    boost::system::error_code & ec) const;
  » more...

Inherited from basic_socket.

Determine the number of bytes available for reading.

std::size_t available() const;

This function is used to determine the number of bytes that may be read without blocking.

Return Value

The number of bytes that may be read without blocking, or 0 if an error occurs.

Exceptions

boost::system::system_error

Thrown on failure.

Inherited from basic_socket.

Determine the number of bytes available for reading.

std::size_t available(
    boost::system::error_code & ec) const;

This function is used to determine the number of bytes that may be read without blocking.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes that may be read without blocking, or 0 if an error occurs.

Construct a basic_raw_socket without opening it.

explicit basic_raw_socket(
    boost::asio::io_service & io_service);
  » more...

Construct and open a basic_raw_socket.

basic_raw_socket(
    boost::asio::io_service & io_service,
    const protocol_type & protocol);
  » more...

Construct a basic_raw_socket, opening it and binding it to the given local endpoint.

basic_raw_socket(
    boost::asio::io_service & io_service,
    const endpoint_type & endpoint);
  » more...

Construct a basic_raw_socket on an existing native socket.

basic_raw_socket(
    boost::asio::io_service & io_service,
    const protocol_type & protocol,
    const native_handle_type & native_socket);
  » more...

Move-construct a basic_raw_socket from another.

basic_raw_socket(
    basic_raw_socket && other);
  » more...

Move-construct a basic_raw_socket from a socket of another protocol type.

template<
    typename Protocol1,
    typename RawSocketService1>
basic_raw_socket(
    basic_raw_socket< Protocol1, RawSocketService1 > && other,
    typename enable_if< is_convertible< Protocol1, Protocol >::value >::type *  = 0);
  » more...

Construct a basic_raw_socket without opening it.

basic_raw_socket(
    boost::asio::io_service & io_service);

This constructor creates a raw socket without opening it. The open() function must be called before data can be sent or received on the socket.

Parameters

io_service

The io_service object that the raw socket will use to dispatch handlers for any asynchronous operations performed on the socket.

Construct and open a basic_raw_socket.

basic_raw_socket(
    boost::asio::io_service & io_service,
    const protocol_type & protocol);

This constructor creates and opens a raw socket.

Parameters

io_service

The io_service object that the raw socket will use to dispatch handlers for any asynchronous operations performed on the socket.

protocol

An object specifying protocol parameters to be used.

Exceptions

boost::system::system_error

Thrown on failure.

Construct a basic_raw_socket, opening it and binding it to the given local endpoint.

basic_raw_socket(
    boost::asio::io_service & io_service,
    const endpoint_type & endpoint);

This constructor creates a raw socket and automatically opens it bound to the specified endpoint on the local machine. The protocol used is the protocol associated with the given endpoint.

Parameters

io_service

The io_service object that the raw socket will use to dispatch handlers for any asynchronous operations performed on the socket.

endpoint

An endpoint on the local machine to which the raw socket will be bound.

Exceptions

boost::system::system_error

Thrown on failure.

Construct a basic_raw_socket on an existing native socket.

basic_raw_socket(
    boost::asio::io_service & io_service,
    const protocol_type & protocol,
    const native_handle_type & native_socket);

This constructor creates a raw socket object to hold an existing native socket.

Parameters

io_service

The io_service object that the raw socket will use to dispatch handlers for any asynchronous operations performed on the socket.

protocol

An object specifying protocol parameters to be used.

native_socket

The new underlying socket implementation.

Exceptions

boost::system::system_error

Thrown on failure.

Move-construct a basic_raw_socket from another.

basic_raw_socket(
    basic_raw_socket && other);

This constructor moves a raw socket from one object to another.

Parameters

other

The other basic_raw_socket object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_raw_socket(io_service&) constructor.

Move-construct a basic_raw_socket from a socket of another protocol type.

template<
    typename Protocol1,
    typename RawSocketService1>
basic_raw_socket(
    basic_raw_socket< Protocol1, RawSocketService1 > && other,
    typename enable_if< is_convertible< Protocol1, Protocol >::value >::type *  = 0);

This constructor moves a raw socket from one object to another.

Parameters

other

The other basic_raw_socket object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_raw_socket(io_service&) constructor.

Bind the socket to the given local endpoint.

void bind(
    const endpoint_type & endpoint);
  » more...

boost::system::error_code bind(
    const endpoint_type & endpoint,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Bind the socket to the given local endpoint.

void bind(
    const endpoint_type & endpoint);

This function binds the socket to the specified endpoint on the local machine.

Parameters

endpoint

An endpoint on the local machine to which the socket will be bound.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::socket socket(io_service);
socket.open(boost::asio::ip::tcp::v4());
socket.bind(boost::asio::ip::tcp::endpoint(
      boost::asio::ip::tcp::v4(), 12345));

Inherited from basic_socket.

Bind the socket to the given local endpoint.

boost::system::error_code bind(
    const endpoint_type & endpoint,
    boost::system::error_code & ec);

This function binds the socket to the specified endpoint on the local machine.

Parameters

endpoint

An endpoint on the local machine to which the socket will be bound.

ec

Set to indicate what error occurred, if any.

Example
boost::asio::ip::tcp::socket socket(io_service);
socket.open(boost::asio::ip::tcp::v4());
boost::system::error_code ec;
socket.bind(boost::asio::ip::tcp::endpoint(
      boost::asio::ip::tcp::v4(), 12345), ec);
if (ec)
{
  // An error occurred.
}

Inherited from socket_base.

Socket option to permit sending of broadcast messages.

typedef implementation_defined broadcast;

Implements the SOL_SOCKET/SO_BROADCAST socket option.

Examples

Setting the option:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::broadcast option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::broadcast option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_raw_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

IO control command to get the amount of data that can be read without blocking.

typedef implementation_defined bytes_readable;

Implements the FIONREAD IO control command.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::bytes_readable command(true);
socket.io_control(command);
std::size_t bytes_readable = command.get();
Requirements

Header: boost/asio/basic_raw_socket.hpp

Convenience header: boost/asio.hpp

Cancel all asynchronous operations associated with the socket.

void cancel();
  » more...

boost::system::error_code cancel(
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Cancel all asynchronous operations associated with the socket.

void cancel();

This function causes all outstanding asynchronous connect, send and receive operations to finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Calls to cancel() will always fail with boost::asio::error::operation_not_supported when run on Windows XP, Windows Server 2003, and earlier versions of Windows, unless BOOST_ASIO_ENABLE_CANCELIO is defined. However, the CancelIo function has two issues that should be considered before enabling its use:

  • It will only cancel asynchronous operations that were initiated in the current thread.
  • It can appear to complete without error, but the request to cancel the unfinished operations may be silently ignored by the operating system. Whether it works or not seems to depend on the drivers that are installed.

For portable cancellation, consider using one of the following alternatives:

  • Disable asio's I/O completion port backend by defining BOOST_ASIO_DISABLE_IOCP.
  • Use the close() function to simultaneously cancel the outstanding operations and close the socket.

When running on Windows Vista, Windows Server 2008, and later, the CancelIoEx function is always used. This function does not have the problems described above.

Inherited from basic_socket.

Cancel all asynchronous operations associated with the socket.

boost::system::error_code cancel(
    boost::system::error_code & ec);

This function causes all outstanding asynchronous connect, send and receive operations to finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error.

Parameters

ec

Set to indicate what error occurred, if any.

Remarks

Calls to cancel() will always fail with boost::asio::error::operation_not_supported when run on Windows XP, Windows Server 2003, and earlier versions of Windows, unless BOOST_ASIO_ENABLE_CANCELIO is defined. However, the CancelIo function has two issues that should be considered before enabling its use:

  • It will only cancel asynchronous operations that were initiated in the current thread.
  • It can appear to complete without error, but the request to cancel the unfinished operations may be silently ignored by the operating system. Whether it works or not seems to depend on the drivers that are installed.

For portable cancellation, consider using one of the following alternatives:

  • Disable asio's I/O completion port backend by defining BOOST_ASIO_DISABLE_IOCP.
  • Use the close() function to simultaneously cancel the outstanding operations and close the socket.

When running on Windows Vista, Windows Server 2008, and later, the CancelIoEx function is always used. This function does not have the problems described above.

Close the socket.

void close();
  » more...

boost::system::error_code close(
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Close the socket.

void close();

This function is used to close the socket. Any asynchronous send, receive or connect operations will be cancelled immediately, and will complete with the boost::asio::error::operation_aborted error.

Exceptions

boost::system::system_error

Thrown on failure. Note that, even if the function indicates an error, the underlying descriptor is closed.

Remarks

For portable behaviour with respect to graceful closure of a connected socket, call shutdown() before closing the socket.

Inherited from basic_socket.

Close the socket.

boost::system::error_code close(
    boost::system::error_code & ec);

This function is used to close the socket. Any asynchronous send, receive or connect operations will be cancelled immediately, and will complete with the boost::asio::error::operation_aborted error.

Parameters

ec

Set to indicate what error occurred, if any. Note that, even if the function indicates an error, the underlying descriptor is closed.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::system::error_code ec;
socket.close(ec);
if (ec)
{
  // An error occurred.
}
Remarks

For portable behaviour with respect to graceful closure of a connected socket, call shutdown() before closing the socket.

Connect the socket to the specified endpoint.

void connect(
    const endpoint_type & peer_endpoint);
  » more...

boost::system::error_code connect(
    const endpoint_type & peer_endpoint,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Connect the socket to the specified endpoint.

void connect(
    const endpoint_type & peer_endpoint);

This function is used to connect a socket to the specified remote endpoint. The function call will block until the connection is successfully made or an error occurs.

The socket is automatically opened if it is not already open. If the connect fails, and the socket was automatically opened, the socket is not returned to the closed state.

Parameters

peer_endpoint

The remote endpoint to which the socket will be connected.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::socket socket(io_service);
boost::asio::ip::tcp::endpoint endpoint(
    boost::asio::ip::address::from_string("1.2.3.4"), 12345);
socket.connect(endpoint);

Inherited from basic_socket.

Connect the socket to the specified endpoint.

boost::system::error_code connect(
    const endpoint_type & peer_endpoint,
    boost::system::error_code & ec);

This function is used to connect a socket to the specified remote endpoint. The function call will block until the connection is successfully made or an error occurs.

The socket is automatically opened if it is not already open. If the connect fails, and the socket was automatically opened, the socket is not returned to the closed state.

Parameters

peer_endpoint

The remote endpoint to which the socket will be connected.

ec

Set to indicate what error occurred, if any.

Example
boost::asio::ip::tcp::socket socket(io_service);
boost::asio::ip::tcp::endpoint endpoint(
    boost::asio::ip::address::from_string("1.2.3.4"), 12345);
boost::system::error_code ec;
socket.connect(endpoint, ec);
if (ec)
{
  // An error occurred.
}

Inherited from socket_base.

Socket option to enable socket-level debugging.

typedef implementation_defined debug;

Implements the SOL_SOCKET/SO_DEBUG socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::debug option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::debug option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_raw_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option to prevent routing, use local interfaces only.

typedef implementation_defined do_not_route;

Implements the SOL_SOCKET/SO_DONTROUTE socket option.

Examples

Setting the option:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::do_not_route option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::do_not_route option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_raw_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option to report aborted connections on accept.

typedef implementation_defined enable_connection_aborted;

Implements a custom socket option that determines whether or not an accept operation is permitted to fail with boost::asio::error::connection_aborted. By default the option is false.

Examples

Setting the option:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::enable_connection_aborted option(true);
acceptor.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::enable_connection_aborted option;
acceptor.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_raw_socket.hpp

Convenience header: boost/asio.hpp

The endpoint type.

typedef Protocol::endpoint endpoint_type;
Requirements

Header: boost/asio/basic_raw_socket.hpp

Convenience header: boost/asio.hpp

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();
  » more...

const implementation_type & get_implementation() const;
  » more...

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

const implementation_type & get_implementation() const;

Inherited from basic_io_object.

Get the io_service associated with the object.

boost::asio::io_service & get_io_service();

This function may be used to obtain the io_service object that the I/O object uses to dispatch handlers for asynchronous operations.

Return Value

A reference to the io_service object that the I/O object will use to dispatch handlers. Ownership is not transferred to the caller.

Get an option from the socket.

void get_option(
    GettableSocketOption & option) const;
  » more...

boost::system::error_code get_option(
    GettableSocketOption & option,
    boost::system::error_code & ec) const;
  » more...

Inherited from basic_socket.

Get an option from the socket.

template<
    typename GettableSocketOption>
void get_option(
    GettableSocketOption & option) const;

This function is used to get the current value of an option on the socket.

Parameters

option

The option value to be obtained from the socket.

Exceptions

boost::system::system_error

Thrown on failure.

Example

Getting the value of the SOL_SOCKET/SO_KEEPALIVE option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::socket::keep_alive option;
socket.get_option(option);
bool is_set = option.value();

Inherited from basic_socket.

Get an option from the socket.

template<
    typename GettableSocketOption>
boost::system::error_code get_option(
    GettableSocketOption & option,
    boost::system::error_code & ec) const;

This function is used to get the current value of an option on the socket.

Parameters

option

The option value to be obtained from the socket.

ec

Set to indicate what error occurred, if any.

Example

Getting the value of the SOL_SOCKET/SO_KEEPALIVE option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::socket::keep_alive option;
boost::system::error_code ec;
socket.get_option(option, ec);
if (ec)
{
  // An error occurred.
}
bool is_set = option.value();

Get the service associated with the I/O object.

service_type & get_service();
  » more...

const service_type & get_service() const;
  » more...

Inherited from basic_io_object.

Get the service associated with the I/O object.

service_type & get_service();

Inherited from basic_io_object.

Get the service associated with the I/O object.

const service_type & get_service() const;

Inherited from basic_io_object.

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

implementation_type implementation;

Inherited from basic_io_object.

The underlying implementation type of I/O object.

typedef service_type::implementation_type implementation_type;
Requirements

Header: boost/asio/basic_raw_socket.hpp

Convenience header: boost/asio.hpp

Perform an IO control command on the socket.

void io_control(
    IoControlCommand & command);
  » more...

boost::system::error_code io_control(
    IoControlCommand & command,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Perform an IO control command on the socket.

template<
    typename IoControlCommand>
void io_control(
    IoControlCommand & command);

This function is used to execute an IO control command on the socket.

Parameters

command

The IO control command to be performed on the socket.

Exceptions

boost::system::system_error

Thrown on failure.

Example

Getting the number of bytes ready to read:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::socket::bytes_readable command;
socket.io_control(command);
std::size_t bytes_readable = command.get();

Inherited from basic_socket.

Perform an IO control command on the socket.

template<
    typename IoControlCommand>
boost::system::error_code io_control(
    IoControlCommand & command,
    boost::system::error_code & ec);

This function is used to execute an IO control command on the socket.

Parameters

command

The IO control command to be performed on the socket.

ec

Set to indicate what error occurred, if any.

Example

Getting the number of bytes ready to read:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::socket::bytes_readable command;
boost::system::error_code ec;
socket.io_control(command, ec);
if (ec)
{
  // An error occurred.
}
std::size_t bytes_readable = command.get();

Inherited from basic_socket.

Determine whether the socket is open.

bool is_open() const;

Inherited from socket_base.

Socket option to send keep-alives.

typedef implementation_defined keep_alive;

Implements the SOL_SOCKET/SO_KEEPALIVE socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::keep_alive option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::keep_alive option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_raw_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

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.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::linger option(true, 30);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::linger option;
socket.get_option(option);
bool is_set = option.enabled();
unsigned short timeout = option.timeout();
Requirements

Header: boost/asio/basic_raw_socket.hpp

Convenience header: boost/asio.hpp

Get the local endpoint of the socket.

endpoint_type local_endpoint() const;
  » more...

endpoint_type local_endpoint(
    boost::system::error_code & ec) const;
  » more...

Inherited from basic_socket.

Get the local endpoint of the socket.

endpoint_type local_endpoint() const;

This function is used to obtain the locally bound endpoint of the socket.

Return Value

An object that represents the local endpoint of the socket.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::endpoint endpoint = socket.local_endpoint();

Inherited from basic_socket.

Get the local endpoint of the socket.

endpoint_type local_endpoint(
    boost::system::error_code & ec) const;

This function is used to obtain the locally bound endpoint of the socket.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

An object that represents the local endpoint of the socket. Returns a default-constructed endpoint object if an error occurred.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::system::error_code ec;
boost::asio::ip::tcp::endpoint endpoint = socket.local_endpoint(ec);
if (ec)
{
  // An error occurred.
}

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();
  » more...

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;
  » more...

Inherited from basic_socket.

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();

This function returns a reference to the lowest layer in a stack of layers. Since a basic_socket cannot contain any further layers, it simply returns a reference to itself.

Return Value

A reference to the lowest layer in the stack of layers. Ownership is not transferred to the caller.

Inherited from basic_socket.

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;

This function returns a const reference to the lowest layer in a stack of layers. Since a basic_socket cannot contain any further layers, it simply returns a reference to itself.

Return Value

A const reference to the lowest layer in the stack of layers. Ownership is not transferred to the caller.

Inherited from basic_socket.

A basic_socket is always the lowest layer.

typedef basic_socket< Protocol, RawSocketService > lowest_layer_type;
Types

Name

Description

broadcast

Socket option to permit sending of broadcast messages.

bytes_readable

IO control command to get the amount of data that can be read without blocking.

debug

Socket option to enable socket-level debugging.

do_not_route

Socket option to prevent routing, use local interfaces only.

enable_connection_aborted

Socket option to report aborted connections on accept.

endpoint_type

The endpoint type.

implementation_type

The underlying implementation type of I/O object.

keep_alive

Socket option to send keep-alives.

linger

Socket option to specify whether the socket lingers on close if unsent data is present.

lowest_layer_type

A basic_socket is always the lowest layer.

message_flags

Bitmask type for flags that can be passed to send and receive operations.

native_handle_type

The native representation of a socket.

native_type

(Deprecated: Use native_handle_type.) The native representation of a socket.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

protocol_type

The protocol type.

receive_buffer_size

Socket option for the receive buffer size of a socket.

receive_low_watermark

Socket option for the receive low watermark.

reuse_address

Socket option to allow the socket to be bound to an address that is already in use.

send_buffer_size

Socket option for the send buffer size of a socket.

send_low_watermark

Socket option for the send low watermark.

service_type

The type of the service that will be used to provide I/O operations.

shutdown_type

Different ways a socket may be shutdown.

Member Functions

Name

Description

assign

Assign an existing native socket to the socket.

async_connect

Start an asynchronous connect.

at_mark

Determine whether the socket is at the out-of-band data mark.

available

Determine the number of bytes available for reading.

basic_socket

Construct a basic_socket without opening it.

Construct and open a basic_socket.

Construct a basic_socket, opening it and binding it to the given local endpoint.

Construct a basic_socket on an existing native socket.

Move-construct a basic_socket from another.

Move-construct a basic_socket from a socket of another protocol type.

bind

Bind the socket to the given local endpoint.

cancel

Cancel all asynchronous operations associated with the socket.

close

Close the socket.

connect

Connect the socket to the specified endpoint.

get_io_service

Get the io_service associated with the object.

get_option

Get an option from the socket.

io_control

Perform an IO control command on the socket.

is_open

Determine whether the socket is open.

local_endpoint

Get the local endpoint of the socket.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native socket representation.

native_handle

Get the native socket representation.

native_non_blocking

Gets the non-blocking mode of the native socket implementation.

Sets the non-blocking mode of the native socket implementation.

non_blocking

Gets the non-blocking mode of the socket.

Sets the non-blocking mode of the socket.

open

Open the socket using the specified protocol.

operator=

Move-assign a basic_socket from another.

Move-assign a basic_socket from a socket of another protocol type.

remote_endpoint

Get the remote endpoint of the socket.

set_option

Set an option on the socket.

shutdown

Disable sends or receives on the socket.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

~basic_socket

Protected destructor to prevent deletion through this type.

Data Members

Name

Description

max_connections

The maximum length of the queue of pending incoming connections.

message_do_not_route

Specify that the data should not be subject to routing.

message_end_of_record

Specifies that the data marks the end of a record.

message_out_of_band

Process out-of-band data.

message_peek

Peek at incoming data without removing it from the input queue.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_socket class template provides functionality that is common to both stream-oriented and datagram-oriented sockets.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/basic_raw_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

The maximum length of the queue of pending incoming connections.

static const int max_connections = implementation_defined;

Inherited from socket_base.

Specify that the data should not be subject to routing.

static const int message_do_not_route = implementation_defined;

Inherited from socket_base.

Specifies that the data marks the end of a record.

static const int message_end_of_record = implementation_defined;

Inherited from socket_base.

Bitmask type for flags that can be passed to send and receive operations.

typedef int message_flags;
Requirements

Header: boost/asio/basic_raw_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Process out-of-band data.

static const int message_out_of_band = implementation_defined;

Inherited from socket_base.

Peek at incoming data without removing it from the input queue.

static const int message_peek = implementation_defined;

Inherited from basic_socket.

(Deprecated: Use native_handle().) Get the native socket representation.

native_type native();

This function may be used to obtain the underlying representation of the socket. This is intended to allow access to native socket functionality that is not otherwise provided.

Inherited from basic_socket.

Get the native socket representation.

native_handle_type native_handle();

This function may be used to obtain the underlying representation of the socket. This is intended to allow access to native socket functionality that is not otherwise provided.

The native representation of a socket.

typedef RawSocketService::native_handle_type native_handle_type;
Requirements

Header: boost/asio/basic_raw_socket.hpp

Convenience header: boost/asio.hpp

Gets the non-blocking mode of the native socket implementation.

bool native_non_blocking() const;
  » more...

Sets the non-blocking mode of the native socket implementation.

void native_non_blocking(
    bool mode);
  » more...

boost::system::error_code native_non_blocking(
    bool mode,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Gets the non-blocking mode of the native socket implementation.

bool native_non_blocking() const;

This function is used to retrieve the non-blocking mode of the underlying native socket. This mode has no effect on the behaviour of the socket object's synchronous operations.

Return Value

true if the underlying socket is in non-blocking mode and direct system calls may fail with boost::asio::error::would_block (or the equivalent system error).

Remarks

The current non-blocking mode is cached by the socket object. Consequently, the return value may be incorrect if the non-blocking mode was set directly on the native socket.

Example

This function is intended to allow the encapsulation of arbitrary non-blocking system calls as asynchronous operations, in a way that is transparent to the user of the socket object. The following example illustrates how Linux's sendfile system call might be encapsulated:

template <typename Handler>
struct sendfile_op
{
  tcp::socket& sock_;
  int fd_;
  Handler handler_;
  off_t offset_;
  std::size_t total_bytes_transferred_;

  // Function call operator meeting WriteHandler requirements.
  // Used as the handler for the async_write_some operation.
  void operator()(boost::system::error_code ec, std::size_t)
  {
    // Put the underlying socket into non-blocking mode.
    if (!ec)
      if (!sock_.native_non_blocking())
        sock_.native_non_blocking(true, ec);

    if (!ec)
    {
      for (;;)
      {
        // Try the system call.
        errno = 0;
        int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536);
        ec = boost::system::error_code(n < 0 ? errno : 0,
            boost::asio::error::get_system_category());
        total_bytes_transferred_ += ec ? 0 : n;

        // Retry operation immediately if interrupted by signal.
        if (ec == boost::asio::error::interrupted)
          continue;

        // Check if we need to run the operation again.
        if (ec == boost::asio::error::would_block
            || ec == boost::asio::error::try_again)
        {
          // We have to wait for the socket to become ready again.
          sock_.async_write_some(boost::asio::null_buffers(), *this);
          return;
        }

        if (ec || n == 0)
        {
          // An error occurred, or we have reached the end of the file.
          // Either way we must exit the loop so we can call the handler.
          break;
        }

        // Loop around to try calling sendfile again.
      }
    }

    // Pass result back to user's handler.
    handler_(ec, total_bytes_transferred_);
  }
};

template <typename Handler>
void async_sendfile(tcp::socket& sock, int fd, Handler h)
{
  sendfile_op<Handler> op = { sock, fd, h, 0, 0 };
  sock.async_write_some(boost::asio::null_buffers(), op);
}

Inherited from basic_socket.

Sets the non-blocking mode of the native socket implementation.

void native_non_blocking(
    bool mode);

This function is used to modify the non-blocking mode of the underlying native socket. It has no effect on the behaviour of the socket object's synchronous operations.

Parameters

mode

If true, the underlying socket is put into non-blocking mode and direct system calls may fail with boost::asio::error::would_block (or the equivalent system error).

Exceptions

boost::system::system_error

Thrown on failure. If the mode is false, but the current value of non_blocking() is true, this function fails with boost::asio::error::invalid_argument, as the combination does not make sense.

Example

This function is intended to allow the encapsulation of arbitrary non-blocking system calls as asynchronous operations, in a way that is transparent to the user of the socket object. The following example illustrates how Linux's sendfile system call might be encapsulated:

template <typename Handler>
struct sendfile_op
{
  tcp::socket& sock_;
  int fd_;
  Handler handler_;
  off_t offset_;
  std::size_t total_bytes_transferred_;

  // Function call operator meeting WriteHandler requirements.
  // Used as the handler for the async_write_some operation.
  void operator()(boost::system::error_code ec, std::size_t)
  {
    // Put the underlying socket into non-blocking mode.
    if (!ec)
      if (!sock_.native_non_blocking())
        sock_.native_non_blocking(true, ec);

    if (!ec)
    {
      for (;;)
      {
        // Try the system call.
        errno = 0;
        int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536);
        ec = boost::system::error_code(n < 0 ? errno : 0,
            boost::asio::error::get_system_category());
        total_bytes_transferred_ += ec ? 0 : n;

        // Retry operation immediately if interrupted by signal.
        if (ec == boost::asio::error::interrupted)
          continue;

        // Check if we need to run the operation again.
        if (ec == boost::asio::error::would_block
            || ec == boost::asio::error::try_again)
        {
          // We have to wait for the socket to become ready again.
          sock_.async_write_some(boost::asio::null_buffers(), *this);
          return;
        }

        if (ec || n == 0)
        {
          // An error occurred, or we have reached the end of the file.
          // Either way we must exit the loop so we can call the handler.
          break;
        }

        // Loop around to try calling sendfile again.
      }
    }

    // Pass result back to user's handler.
    handler_(ec, total_bytes_transferred_);
  }
};

template <typename Handler>
void async_sendfile(tcp::socket& sock, int fd, Handler h)
{
  sendfile_op<Handler> op = { sock, fd, h, 0, 0 };
  sock.async_write_some(boost::asio::null_buffers(), op);
}

Inherited from basic_socket.

Sets the non-blocking mode of the native socket implementation.

boost::system::error_code native_non_blocking(
    bool mode,
    boost::system::error_code & ec);

This function is used to modify the non-blocking mode of the underlying native socket. It has no effect on the behaviour of the socket object's synchronous operations.

Parameters

mode

If true, the underlying socket is put into non-blocking mode and direct system calls may fail with boost::asio::error::would_block (or the equivalent system error).

ec

Set to indicate what error occurred, if any. If the mode is false, but the current value of non_blocking() is true, this function fails with boost::asio::error::invalid_argument, as the combination does not make sense.

Example

This function is intended to allow the encapsulation of arbitrary non-blocking system calls as asynchronous operations, in a way that is transparent to the user of the socket object. The following example illustrates how Linux's sendfile system call might be encapsulated:

template <typename Handler>
struct sendfile_op
{
  tcp::socket& sock_;
  int fd_;
  Handler handler_;
  off_t offset_;
  std::size_t total_bytes_transferred_;

  // Function call operator meeting WriteHandler requirements.
  // Used as the handler for the async_write_some operation.
  void operator()(boost::system::error_code ec, std::size_t)
  {
    // Put the underlying socket into non-blocking mode.
    if (!ec)
      if (!sock_.native_non_blocking())
        sock_.native_non_blocking(true, ec);

    if (!ec)
    {
      for (;;)
      {
        // Try the system call.
        errno = 0;
        int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536);
        ec = boost::system::error_code(n < 0 ? errno : 0,
            boost::asio::error::get_system_category());
        total_bytes_transferred_ += ec ? 0 : n;

        // Retry operation immediately if interrupted by signal.
        if (ec == boost::asio::error::interrupted)
          continue;

        // Check if we need to run the operation again.
        if (ec == boost::asio::error::would_block
            || ec == boost::asio::error::try_again)
        {
          // We have to wait for the socket to become ready again.
          sock_.async_write_some(boost::asio::null_buffers(), *this);
          return;
        }

        if (ec || n == 0)
        {
          // An error occurred, or we have reached the end of the file.
          // Either way we must exit the loop so we can call the handler.
          break;
        }

        // Loop around to try calling sendfile again.
      }
    }

    // Pass result back to user's handler.
    handler_(ec, total_bytes_transferred_);
  }
};

template <typename Handler>
void async_sendfile(tcp::socket& sock, int fd, Handler h)
{
  sendfile_op<Handler> op = { sock, fd, h, 0, 0 };
  sock.async_write_some(boost::asio::null_buffers(), op);
}

(Deprecated: Use native_handle_type.) The native representation of a socket.

typedef RawSocketService::native_handle_type native_type;
Requirements

Header: boost/asio/basic_raw_socket.hpp

Convenience header: boost/asio.hpp

Gets the non-blocking mode of the socket.

bool non_blocking() const;
  » more...

Sets the non-blocking mode of the socket.

void non_blocking(
    bool mode);
  » more...

boost::system::error_code non_blocking(
    bool mode,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Gets the non-blocking mode of the socket.

bool non_blocking() const;
Return Value

true if the socket's synchronous operations will fail with boost::asio::error::would_block if they are unable to perform the requested operation immediately. If false, synchronous operations will block until complete.

Remarks

The non-blocking mode has no effect on the behaviour of asynchronous operations. Asynchronous operations will never fail with the error boost::asio::error::would_block.

Inherited from basic_socket.

Sets the non-blocking mode of the socket.

void non_blocking(
    bool mode);
Parameters

mode

If true, the socket's synchronous operations will fail with boost::asio::error::would_block if they are unable to perform the requested operation immediately. If false, synchronous operations will block until complete.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

The non-blocking mode has no effect on the behaviour of asynchronous operations. Asynchronous operations will never fail with the error boost::asio::error::would_block.

Inherited from basic_socket.

Sets the non-blocking mode of the socket.

boost::system::error_code non_blocking(
    bool mode,
    boost::system::error_code & ec);
Parameters

mode

If true, the socket's synchronous operations will fail with boost::asio::error::would_block if they are unable to perform the requested operation immediately. If false, synchronous operations will block until complete.

ec

Set to indicate what error occurred, if any.

Remarks

The non-blocking mode has no effect on the behaviour of asynchronous operations. Asynchronous operations will never fail with the error boost::asio::error::would_block.

Inherited from socket_base.

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

typedef implementation_defined non_blocking_io;

Implements the FIONBIO IO control command.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::non_blocking_io command(true);
socket.io_control(command);
Requirements

Header: boost/asio/basic_raw_socket.hpp

Convenience header: boost/asio.hpp

Open the socket using the specified protocol.

void open(
    const protocol_type & protocol = protocol_type());
  » more...

boost::system::error_code open(
    const protocol_type & protocol,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Open the socket using the specified protocol.

void open(
    const protocol_type & protocol = protocol_type());

This function opens the socket so that it will use the specified protocol.

Parameters

protocol

An object specifying protocol parameters to be used.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::socket socket(io_service);
socket.open(boost::asio::ip::tcp::v4());

Inherited from basic_socket.

Open the socket using the specified protocol.

boost::system::error_code open(
    const protocol_type & protocol,
    boost::system::error_code & ec);

This function opens the socket so that it will use the specified protocol.

Parameters

protocol

An object specifying which protocol is to be used.

ec

Set to indicate what error occurred, if any.

Example
boost::asio::ip::tcp::socket socket(io_service);
boost::system::error_code ec;
socket.open(boost::asio::ip::tcp::v4(), ec);
if (ec)
{
  // An error occurred.
}

Move-assign a basic_raw_socket from another.

basic_raw_socket & operator=(
    basic_raw_socket && other);
  » more...

Move-assign a basic_raw_socket from a socket of another protocol type.

template<
    typename Protocol1,
    typename RawSocketService1>
enable_if< is_convertible< Protocol1, Protocol >::value, basic_raw_socket >::type & operator=(
    basic_raw_socket< Protocol1, RawSocketService1 > && other);
  » more...

Move-assign a basic_raw_socket from another.

basic_raw_socket & operator=(
    basic_raw_socket && other);

This assignment operator moves a raw socket from one object to another.

Parameters

other

The other basic_raw_socket object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_raw_socket(io_service&) constructor.

Move-assign a basic_raw_socket from a socket of another protocol type.

template<
    typename Protocol1,
    typename RawSocketService1>
enable_if< is_convertible< Protocol1, Protocol >::value, basic_raw_socket >::type & operator=(
    basic_raw_socket< Protocol1, RawSocketService1 > && other);

This assignment operator moves a raw socket from one object to another.

Parameters

other

The other basic_raw_socket object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_raw_socket(io_service&) constructor.

The protocol type.

typedef Protocol protocol_type;
Requirements

Header: boost/asio/basic_raw_socket.hpp

Convenience header: boost/asio.hpp

Receive some data on a connected socket.

template<
    typename MutableBufferSequence>
std::size_t receive(
    const MutableBufferSequence & buffers);
  » more...

template<
    typename MutableBufferSequence>
std::size_t receive(
    const MutableBufferSequence & buffers,
    socket_base::message_flags flags);
  » more...

template<
    typename MutableBufferSequence>
std::size_t receive(
    const MutableBufferSequence & buffers,
    socket_base::message_flags flags,
    boost::system::error_code & ec);
  » more...

Receive some data on a connected socket.

template<
    typename MutableBufferSequence>
std::size_t receive(
    const MutableBufferSequence & buffers);

This function is used to receive data on the raw socket. The function call will block until data has been received successfully or an error occurs.

Parameters

buffers

One or more buffers into which the data will be received.

Return Value

The number of bytes received.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

The receive operation can only be used with a connected socket. Use the receive_from function to receive data on an unconnected raw socket.

Example

To receive into a single data buffer use the buffer function as follows:

socket.receive(boost::asio::buffer(data, size));

See the buffer documentation for information on receiving into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Receive some data on a connected socket.

template<
    typename MutableBufferSequence>
std::size_t receive(
    const MutableBufferSequence & buffers,
    socket_base::message_flags flags);

This function is used to receive data on the raw socket. The function call will block until data has been received successfully or an error occurs.

Parameters

buffers

One or more buffers into which the data will be received.

flags

Flags specifying how the receive call is to be made.

Return Value

The number of bytes received.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

The receive operation can only be used with a connected socket. Use the receive_from function to receive data on an unconnected raw socket.

Receive some data on a connected socket.

template<
    typename MutableBufferSequence>
std::size_t receive(
    const MutableBufferSequence & buffers,
    socket_base::message_flags flags,
    boost::system::error_code & ec);

This function is used to receive data on the raw socket. The function call will block until data has been received successfully or an error occurs.

Parameters

buffers

One or more buffers into which the data will be received.

flags

Flags specifying how the receive call is to be made.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes received.

Remarks

The receive operation can only be used with a connected socket. Use the receive_from function to receive data on an unconnected raw socket.

Inherited from socket_base.

Socket option for the receive buffer size of a socket.

typedef implementation_defined receive_buffer_size;

Implements the SOL_SOCKET/SO_RCVBUF socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_buffer_size option(8192);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_buffer_size option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/basic_raw_socket.hpp

Convenience header: boost/asio.hpp

Receive raw data with the endpoint of the sender.

template<
    typename MutableBufferSequence>
std::size_t receive_from(
    const MutableBufferSequence & buffers,
    endpoint_type & sender_endpoint);
  » more...

template<
    typename MutableBufferSequence>
std::size_t receive_from(
    const MutableBufferSequence & buffers,
    endpoint_type & sender_endpoint,
    socket_base::message_flags flags);
  » more...

template<
    typename MutableBufferSequence>
std::size_t receive_from(
    const MutableBufferSequence & buffers,
    endpoint_type & sender_endpoint,
    socket_base::message_flags flags,
    boost::system::error_code & ec);
  » more...

Receive raw data with the endpoint of the sender.

template<
    typename MutableBufferSequence>
std::size_t receive_from(
    const MutableBufferSequence & buffers,
    endpoint_type & sender_endpoint);

This function is used to receive raw data. The function call will block until data has been received successfully or an error occurs.

Parameters

buffers

One or more buffers into which the data will be received.

sender_endpoint

An endpoint object that receives the endpoint of the remote sender of the data.

Return Value

The number of bytes received.

Exceptions

boost::system::system_error

Thrown on failure.

Example

To receive into a single data buffer use the buffer function as follows:

boost::asio::ip::udp::endpoint sender_endpoint;
socket.receive_from(
    boost::asio::buffer(data, size), sender_endpoint);

See the buffer documentation for information on receiving into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Receive raw data with the endpoint of the sender.

template<
    typename MutableBufferSequence>
std::size_t receive_from(
    const MutableBufferSequence & buffers,
    endpoint_type & sender_endpoint,
    socket_base::message_flags flags);

This function is used to receive raw data. The function call will block until data has been received successfully or an error occurs.

Parameters

buffers

One or more buffers into which the data will be received.

sender_endpoint

An endpoint object that receives the endpoint of the remote sender of the data.

flags

Flags specifying how the receive call is to be made.

Return Value

The number of bytes received.

Exceptions

boost::system::system_error

Thrown on failure.

Receive raw data with the endpoint of the sender.

template<
    typename MutableBufferSequence>
std::size_t receive_from(
    const MutableBufferSequence & buffers,
    endpoint_type & sender_endpoint,
    socket_base::message_flags flags,
    boost::system::error_code & ec);

This function is used to receive raw data. The function call will block until data has been received successfully or an error occurs.

Parameters

buffers

One or more buffers into which the data will be received.

sender_endpoint

An endpoint object that receives the endpoint of the remote sender of the data.

flags

Flags specifying how the receive call is to be made.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes received.

Inherited from socket_base.

Socket option for the receive low watermark.

typedef implementation_defined receive_low_watermark;

Implements the SOL_SOCKET/SO_RCVLOWAT socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_low_watermark option(1024);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_low_watermark option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/basic_raw_socket.hpp

Convenience header: boost/asio.hpp

Get the remote endpoint of the socket.

endpoint_type remote_endpoint() const;
  » more...

endpoint_type remote_endpoint(
    boost::system::error_code & ec) const;
  » more...

Inherited from basic_socket.

Get the remote endpoint of the socket.

endpoint_type remote_endpoint() const;

This function is used to obtain the remote endpoint of the socket.

Return Value

An object that represents the remote endpoint of the socket.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::endpoint endpoint = socket.remote_endpoint();

Inherited from basic_socket.

Get the remote endpoint of the socket.

endpoint_type remote_endpoint(
    boost::system::error_code & ec) const;

This function is used to obtain the remote endpoint of the socket.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

An object that represents the remote endpoint of the socket. Returns a default-constructed endpoint object if an error occurred.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::system::error_code ec;
boost::asio::ip::tcp::endpoint endpoint = socket.remote_endpoint(ec);
if (ec)
{
  // An error occurred.
}

Inherited from socket_base.

Socket option to allow the socket to be bound to an address that is already in use.

typedef implementation_defined reuse_address;

Implements the SOL_SOCKET/SO_REUSEADDR socket option.

Examples

Setting the option:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::reuse_address option(true);
acceptor.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::reuse_address option;
acceptor.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_raw_socket.hpp

Convenience header: boost/asio.hpp

Send some data on a connected socket.

template<
    typename ConstBufferSequence>
std::size_t send(
    const ConstBufferSequence & buffers);
  » more...

template<
    typename ConstBufferSequence>
std::size_t send(
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags);
  » more...

template<
    typename ConstBufferSequence>
std::size_t send(
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags,
    boost::system::error_code & ec);
  » more...

Send some data on a connected socket.

template<
    typename ConstBufferSequence>
std::size_t send(
    const ConstBufferSequence & buffers);

This function is used to send data on the raw socket. The function call will block until the data has been sent successfully or an error occurs.

Parameters

buffers

One ore more data buffers to be sent on the socket.

Return Value

The number of bytes sent.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

The send operation can only be used with a connected socket. Use the send_to function to send data on an unconnected raw socket.

Example

To send a single data buffer use the buffer function as follows:

socket.send(boost::asio::buffer(data, size));

See the buffer documentation for information on sending multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Send some data on a connected socket.

template<
    typename ConstBufferSequence>
std::size_t send(
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags);

This function is used to send data on the raw socket. The function call will block until the data has been sent successfully or an error occurs.

Parameters

buffers

One ore more data buffers to be sent on the socket.

flags

Flags specifying how the send call is to be made.

Return Value

The number of bytes sent.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

The send operation can only be used with a connected socket. Use the send_to function to send data on an unconnected raw socket.

Send some data on a connected socket.

template<
    typename ConstBufferSequence>
std::size_t send(
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags,
    boost::system::error_code & ec);

This function is used to send data on the raw socket. The function call will block until the data has been sent successfully or an error occurs.

Parameters

buffers

One or more data buffers to be sent on the socket.

flags

Flags specifying how the send call is to be made.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes sent.

Remarks

The send operation can only be used with a connected socket. Use the send_to function to send data on an unconnected raw socket.

Inherited from socket_base.

Socket option for the send buffer size of a socket.

typedef implementation_defined send_buffer_size;

Implements the SOL_SOCKET/SO_SNDBUF socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_buffer_size option(8192);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_buffer_size option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/basic_raw_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option for the send low watermark.

typedef implementation_defined send_low_watermark;

Implements the SOL_SOCKET/SO_SNDLOWAT socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_low_watermark option(1024);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_low_watermark option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/basic_raw_socket.hpp

Convenience header: boost/asio.hpp

Send raw data to the specified endpoint.

template<
    typename ConstBufferSequence>
std::size_t send_to(
    const ConstBufferSequence & buffers,
    const endpoint_type & destination);
  » more...

template<
    typename ConstBufferSequence>
std::size_t send_to(
    const ConstBufferSequence & buffers,
    const endpoint_type & destination,
    socket_base::message_flags flags);
  » more...

template<
    typename ConstBufferSequence>
std::size_t send_to(
    const ConstBufferSequence & buffers,
    const endpoint_type & destination,
    socket_base::message_flags flags,
    boost::system::error_code & ec);
  » more...

Send raw data to the specified endpoint.

template<
    typename ConstBufferSequence>
std::size_t send_to(
    const ConstBufferSequence & buffers,
    const endpoint_type & destination);

This function is used to send raw data to the specified remote endpoint. The function call will block until the data has been sent successfully or an error occurs.

Parameters

buffers

One or more data buffers to be sent to the remote endpoint.

destination

The remote endpoint to which the data will be sent.

Return Value

The number of bytes sent.

Exceptions

boost::system::system_error

Thrown on failure.

Example

To send a single data buffer use the buffer function as follows:

boost::asio::ip::udp::endpoint destination(
    boost::asio::ip::address::from_string("1.2.3.4"), 12345);
socket.send_to(boost::asio::buffer(data, size), destination);

See the buffer documentation for information on sending multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Send raw data to the specified endpoint.

template<
    typename ConstBufferSequence>
std::size_t send_to(
    const ConstBufferSequence & buffers,
    const endpoint_type & destination,
    socket_base::message_flags flags);

This function is used to send raw data to the specified remote endpoint. The function call will block until the data has been sent successfully or an error occurs.

Parameters

buffers

One or more data buffers to be sent to the remote endpoint.

destination

The remote endpoint to which the data will be sent.

flags

Flags specifying how the send call is to be made.

Return Value

The number of bytes sent.

Exceptions

boost::system::system_error

Thrown on failure.

Send raw data to the specified endpoint.

template<
    typename ConstBufferSequence>
std::size_t send_to(
    const ConstBufferSequence & buffers,
    const endpoint_type & destination,
    socket_base::message_flags flags,
    boost::system::error_code & ec);

This function is used to send raw data to the specified remote endpoint. The function call will block until the data has been sent successfully or an error occurs.

Parameters

buffers

One or more data buffers to be sent to the remote endpoint.

destination

The remote endpoint to which the data will be sent.

flags

Flags specifying how the send call is to be made.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes sent.

Inherited from basic_io_object.

(Deprecated: Use get_service().) The service associated with the I/O object.

service_type & service;
Remarks

Available only for services that do not support movability.

Inherited from basic_io_object.

The type of the service that will be used to provide I/O operations.

typedef RawSocketService service_type;
Requirements

Header: boost/asio/basic_raw_socket.hpp

Convenience header: boost/asio.hpp

Set an option on the socket.

void set_option(
    const SettableSocketOption & option);
  » more...

boost::system::error_code set_option(
    const SettableSocketOption & option,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

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.

Parameters

option

The new option value to be set on the socket.

Exceptions

boost::system::system_error

Thrown on failure.

Example

Setting the IPPROTO_TCP/TCP_NODELAY option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::no_delay option(true);
socket.set_option(option);

Inherited from basic_socket.

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.

Parameters

option

The new option value to be set on the socket.

ec

Set to indicate what error occurred, if any.

Example

Setting the IPPROTO_TCP/TCP_NODELAY option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::no_delay option(true);
boost::system::error_code ec;
socket.set_option(option, ec);
if (ec)
{
  // An error occurred.
}

Disable sends or receives on the socket.

void shutdown(
    shutdown_type what);
  » more...

boost::system::error_code shutdown(
    shutdown_type what,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Disable sends or receives on the socket.

void shutdown(
    shutdown_type what);

This function is used to disable send operations, receive operations, or both.

Parameters

what

Determines what types of operation will no longer be allowed.

Exceptions

boost::system::system_error

Thrown on failure.

Example

Shutting down the send side of the socket:

boost::asio::ip::tcp::socket socket(io_service);
...
socket.shutdown(boost::asio::ip::tcp::socket::shutdown_send);

Inherited from basic_socket.

Disable sends or receives on the socket.

boost::system::error_code shutdown(
    shutdown_type what,
    boost::system::error_code & ec);

This function is used to disable send operations, receive operations, or both.

Parameters

what

Determines what types of operation will no longer be allowed.

ec

Set to indicate what error occurred, if any.

Example

Shutting down the send side of the socket:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::system::error_code ec;
socket.shutdown(boost::asio::ip::tcp::socket::shutdown_send, ec);
if (ec)
{
  // An error occurred.
}

Inherited from socket_base.

Different ways a socket may be shutdown.

enum shutdown_type

Values

shutdown_receive

Shutdown the receive side of the socket.

shutdown_send

Shutdown the send side of the socket.

shutdown_both

Shutdown both send and receive on the socket.

basic_seq_packet_socket::assign
basic_seq_packet_socket::async_connect
basic_seq_packet_socket::async_receive
basic_seq_packet_socket::async_send
basic_seq_packet_socket::at_mark
basic_seq_packet_socket::available
basic_seq_packet_socket::basic_seq_packet_socket
basic_seq_packet_socket::bind
basic_seq_packet_socket::broadcast
basic_seq_packet_socket::bytes_readable
basic_seq_packet_socket::cancel
basic_seq_packet_socket::close
basic_seq_packet_socket::connect
basic_seq_packet_socket::debug
basic_seq_packet_socket::do_not_route
basic_seq_packet_socket::enable_connection_aborted
basic_seq_packet_socket::endpoint_type
basic_seq_packet_socket::get_implementation
basic_seq_packet_socket::get_io_service
basic_seq_packet_socket::get_option
basic_seq_packet_socket::get_service
basic_seq_packet_socket::implementation
basic_seq_packet_socket::implementation_type
basic_seq_packet_socket::io_control
basic_seq_packet_socket::is_open
basic_seq_packet_socket::keep_alive
basic_seq_packet_socket::linger
basic_seq_packet_socket::local_endpoint
basic_seq_packet_socket::lowest_layer
basic_seq_packet_socket::lowest_layer_type
basic_seq_packet_socket::max_connections
basic_seq_packet_socket::message_do_not_route
basic_seq_packet_socket::message_end_of_record
basic_seq_packet_socket::message_flags
basic_seq_packet_socket::message_out_of_band
basic_seq_packet_socket::message_peek
basic_seq_packet_socket::native
basic_seq_packet_socket::native_handle
basic_seq_packet_socket::native_handle_type
basic_seq_packet_socket::native_non_blocking
basic_seq_packet_socket::native_type
basic_seq_packet_socket::non_blocking
basic_seq_packet_socket::non_blocking_io
basic_seq_packet_socket::open
basic_seq_packet_socket::operator=
basic_seq_packet_socket::protocol_type
basic_seq_packet_socket::receive
basic_seq_packet_socket::receive_buffer_size
basic_seq_packet_socket::receive_low_watermark
basic_seq_packet_socket::remote_endpoint
basic_seq_packet_socket::reuse_address
basic_seq_packet_socket::send
basic_seq_packet_socket::send_buffer_size
basic_seq_packet_socket::send_low_watermark
basic_seq_packet_socket::service
basic_seq_packet_socket::service_type
basic_seq_packet_socket::set_option
basic_seq_packet_socket::shutdown
basic_seq_packet_socket::shutdown_type

Provides sequenced packet socket functionality.

template<
    typename Protocol,
    typename SeqPacketSocketService = seq_packet_socket_service<Protocol>>
class basic_seq_packet_socket :
  public basic_socket< Protocol, SeqPacketSocketService >
Types

Name

Description

broadcast

Socket option to permit sending of broadcast messages.

bytes_readable

IO control command to get the amount of data that can be read without blocking.

debug

Socket option to enable socket-level debugging.

do_not_route

Socket option to prevent routing, use local interfaces only.

enable_connection_aborted

Socket option to report aborted connections on accept.

endpoint_type

The endpoint type.

implementation_type

The underlying implementation type of I/O object.

keep_alive

Socket option to send keep-alives.

linger

Socket option to specify whether the socket lingers on close if unsent data is present.

lowest_layer_type

A basic_socket is always the lowest layer.

message_flags

Bitmask type for flags that can be passed to send and receive operations.

native_handle_type

The native representation of a socket.

native_type

(Deprecated: Use native_handle_type.) The native representation of a socket.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

protocol_type

The protocol type.

receive_buffer_size

Socket option for the receive buffer size of a socket.

receive_low_watermark

Socket option for the receive low watermark.

reuse_address

Socket option to allow the socket to be bound to an address that is already in use.

send_buffer_size

Socket option for the send buffer size of a socket.

send_low_watermark

Socket option for the send low watermark.

service_type

The type of the service that will be used to provide I/O operations.

shutdown_type

Different ways a socket may be shutdown.

Member Functions

Name

Description

assign

Assign an existing native socket to the socket.

async_connect

Start an asynchronous connect.

async_receive

Start an asynchronous receive.

async_send

Start an asynchronous send.

at_mark

Determine whether the socket is at the out-of-band data mark.

available

Determine the number of bytes available for reading.

basic_seq_packet_socket

Construct a basic_seq_packet_socket without opening it.

Construct and open a basic_seq_packet_socket.

Construct a basic_seq_packet_socket, opening it and binding it to the given local endpoint.

Construct a basic_seq_packet_socket on an existing native socket.

Move-construct a basic_seq_packet_socket from another.

Move-construct a basic_seq_packet_socket from a socket of another protocol type.

bind

Bind the socket to the given local endpoint.

cancel

Cancel all asynchronous operations associated with the socket.

close

Close the socket.

connect

Connect the socket to the specified endpoint.

get_io_service

Get the io_service associated with the object.

get_option

Get an option from the socket.

io_control

Perform an IO control command on the socket.

is_open

Determine whether the socket is open.

local_endpoint

Get the local endpoint of the socket.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native socket representation.

native_handle

Get the native socket representation.

native_non_blocking

Gets the non-blocking mode of the native socket implementation.

Sets the non-blocking mode of the native socket implementation.

non_blocking

Gets the non-blocking mode of the socket.

Sets the non-blocking mode of the socket.

open

Open the socket using the specified protocol.

operator=

Move-assign a basic_seq_packet_socket from another.

Move-assign a basic_seq_packet_socket from a socket of another protocol type.

receive

Receive some data on the socket.

Receive some data on a connected socket.

remote_endpoint

Get the remote endpoint of the socket.

send

Send some data on the socket.

set_option

Set an option on the socket.

shutdown

Disable sends or receives on the socket.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Data Members

Name

Description

max_connections

The maximum length of the queue of pending incoming connections.

message_do_not_route

Specify that the data should not be subject to routing.

message_end_of_record

Specifies that the data marks the end of a record.

message_out_of_band

Process out-of-band data.

message_peek

Peek at incoming data without removing it from the input queue.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_seq_packet_socket class template provides asynchronous and blocking sequenced packet socket functionality.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/basic_seq_packet_socket.hpp

Convenience header: boost/asio.hpp

Assign an existing native socket to the socket.

void assign(
    const protocol_type & protocol,
    const native_handle_type & native_socket);
  » more...

boost::system::error_code assign(
    const protocol_type & protocol,
    const native_handle_type & native_socket,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Assign an existing native socket to the socket.

void assign(
    const protocol_type & protocol,
    const native_handle_type & native_socket);

Inherited from basic_socket.

Assign an existing native socket to the socket.

boost::system::error_code assign(
    const protocol_type & protocol,
    const native_handle_type & native_socket,
    boost::system::error_code & ec);

Inherited from basic_socket.

Start an asynchronous connect.

template<
    typename ConnectHandler>
void-or-deduced async_connect(
    const endpoint_type & peer_endpoint,
    ConnectHandler handler);

This function is used to asynchronously connect a socket to the specified remote endpoint. The function call always returns immediately.

The socket is automatically opened if it is not already open. If the connect fails, and the socket was automatically opened, the socket is not returned to the closed state.

Parameters

peer_endpoint

The remote endpoint to which the socket will be connected. Copies will be made of the endpoint object as required.

handler

The handler to be called when the connection operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error // Result of operation
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Example
void connect_handler(const boost::system::error_code& error)
{
  if (!error)
  {
    // Connect succeeded.
  }
}

...

boost::asio::ip::tcp::socket socket(io_service);
boost::asio::ip::tcp::endpoint endpoint(
    boost::asio::ip::address::from_string("1.2.3.4"), 12345);
socket.async_connect(endpoint, connect_handler);

Start an asynchronous receive.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_receive(
    const MutableBufferSequence & buffers,
    socket_base::message_flags & out_flags,
    ReadHandler handler);
  » more...

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_receive(
    const MutableBufferSequence & buffers,
    socket_base::message_flags in_flags,
    socket_base::message_flags & out_flags,
    ReadHandler handler);
  » more...

Start an asynchronous receive.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_receive(
    const MutableBufferSequence & buffers,
    socket_base::message_flags & out_flags,
    ReadHandler handler);

This function is used to asynchronously receive data from the sequenced packet socket. The function call always returns immediately.

Parameters

buffers

One or more buffers into which the data will be received. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

out_flags

Once the asynchronous operation completes, contains flags associated with the received data. For example, if the socket_base::message_end_of_record bit is set then the received data marks the end of a record. The caller must guarantee that the referenced variable remains valid until the handler is called.

handler

The handler to be called when the receive operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes received.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Example

To receive into a single data buffer use the buffer function as follows:

socket.async_receive(boost::asio::buffer(data, size), out_flags, handler);

See the buffer documentation for information on receiving into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Start an asynchronous receive.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_receive(
    const MutableBufferSequence & buffers,
    socket_base::message_flags in_flags,
    socket_base::message_flags & out_flags,
    ReadHandler handler);

This function is used to asynchronously receive data from the sequenced data socket. The function call always returns immediately.

Parameters

buffers

One or more buffers into which the data will be received. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

in_flags

Flags specifying how the receive call is to be made.

out_flags

Once the asynchronous operation completes, contains flags associated with the received data. For example, if the socket_base::message_end_of_record bit is set then the received data marks the end of a record. The caller must guarantee that the referenced variable remains valid until the handler is called.

handler

The handler to be called when the receive operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes received.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Example

To receive into a single data buffer use the buffer function as follows:

socket.async_receive(
    boost::asio::buffer(data, size),
    0, out_flags, handler);

See the buffer documentation for information on receiving into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Start an asynchronous send.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_send(
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags,
    WriteHandler handler);

This function is used to asynchronously send data on the sequenced packet socket. The function call always returns immediately.

Parameters

buffers

One or more data buffers to be sent on the socket. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

flags

Flags specifying how the send call is to be made.

handler

The handler to be called when the send operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes sent.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Example

To send a single data buffer use the buffer function as follows:

socket.async_send(boost::asio::buffer(data, size), 0, handler);

See the buffer documentation for information on sending multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Determine whether the socket is at the out-of-band data mark.

bool at_mark() const;
  » more...

bool at_mark(
    boost::system::error_code & ec) const;
  » more...

Inherited from basic_socket.

Determine whether the socket is at the out-of-band data mark.

bool at_mark() const;

This function is used to check whether the socket input is currently positioned at the out-of-band data mark.

Return Value

A bool indicating whether the socket is at the out-of-band data mark.

Exceptions

boost::system::system_error

Thrown on failure.

Inherited from basic_socket.

Determine whether the socket is at the out-of-band data mark.

bool at_mark(
    boost::system::error_code & ec) const;

This function is used to check whether the socket input is currently positioned at the out-of-band data mark.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

A bool indicating whether the socket is at the out-of-band data mark.

Determine the number of bytes available for reading.

std::size_t available() const;
  » more...

std::size_t available(
    boost::system::error_code & ec) const;
  » more...

Inherited from basic_socket.

Determine the number of bytes available for reading.

std::size_t available() const;

This function is used to determine the number of bytes that may be read without blocking.

Return Value

The number of bytes that may be read without blocking, or 0 if an error occurs.

Exceptions

boost::system::system_error

Thrown on failure.

Inherited from basic_socket.

Determine the number of bytes available for reading.

std::size_t available(
    boost::system::error_code & ec) const;

This function is used to determine the number of bytes that may be read without blocking.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes that may be read without blocking, or 0 if an error occurs.

Construct a basic_seq_packet_socket without opening it.

explicit basic_seq_packet_socket(
    boost::asio::io_service & io_service);
  » more...

Construct and open a basic_seq_packet_socket.

basic_seq_packet_socket(
    boost::asio::io_service & io_service,
    const protocol_type & protocol);
  » more...

Construct a basic_seq_packet_socket, opening it and binding it to the given local endpoint.

basic_seq_packet_socket(
    boost::asio::io_service & io_service,
    const endpoint_type & endpoint);
  » more...

Construct a basic_seq_packet_socket on an existing native socket.

basic_seq_packet_socket(
    boost::asio::io_service & io_service,
    const protocol_type & protocol,
    const native_handle_type & native_socket);
  » more...

Move-construct a basic_seq_packet_socket from another.

basic_seq_packet_socket(
    basic_seq_packet_socket && other);
  » more...

Move-construct a basic_seq_packet_socket from a socket of another protocol type.

template<
    typename Protocol1,
    typename SeqPacketSocketService1>
basic_seq_packet_socket(
    basic_seq_packet_socket< Protocol1, SeqPacketSocketService1 > && other,
    typename enable_if< is_convertible< Protocol1, Protocol >::value >::type *  = 0);
  » more...

Construct a basic_seq_packet_socket without opening it.

basic_seq_packet_socket(
    boost::asio::io_service & io_service);

This constructor creates a sequenced packet socket without opening it. The socket needs to be opened and then connected or accepted before data can be sent or received on it.

Parameters

io_service

The io_service object that the sequenced packet socket will use to dispatch handlers for any asynchronous operations performed on the socket.

Construct and open a basic_seq_packet_socket.

basic_seq_packet_socket(
    boost::asio::io_service & io_service,
    const protocol_type & protocol);

This constructor creates and opens a sequenced_packet socket. The socket needs to be connected or accepted before data can be sent or received on it.

Parameters

io_service

The io_service object that the sequenced packet socket will use to dispatch handlers for any asynchronous operations performed on the socket.

protocol

An object specifying protocol parameters to be used.

Exceptions

boost::system::system_error

Thrown on failure.

Construct a basic_seq_packet_socket, opening it and binding it to the given local endpoint.

basic_seq_packet_socket(
    boost::asio::io_service & io_service,
    const endpoint_type & endpoint);

This constructor creates a sequenced packet socket and automatically opens it bound to the specified endpoint on the local machine. The protocol used is the protocol associated with the given endpoint.

Parameters

io_service

The io_service object that the sequenced packet socket will use to dispatch handlers for any asynchronous operations performed on the socket.

endpoint

An endpoint on the local machine to which the sequenced packet socket will be bound.

Exceptions

boost::system::system_error

Thrown on failure.

Construct a basic_seq_packet_socket on an existing native socket.

basic_seq_packet_socket(
    boost::asio::io_service & io_service,
    const protocol_type & protocol,
    const native_handle_type & native_socket);

This constructor creates a sequenced packet socket object to hold an existing native socket.

Parameters

io_service

The io_service object that the sequenced packet socket will use to dispatch handlers for any asynchronous operations performed on the socket.

protocol

An object specifying protocol parameters to be used.

native_socket

The new underlying socket implementation.

Exceptions

boost::system::system_error

Thrown on failure.

Move-construct a basic_seq_packet_socket from another.

basic_seq_packet_socket(
    basic_seq_packet_socket && other);

This constructor moves a sequenced packet socket from one object to another.

Parameters

other

The other basic_seq_packet_socket object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_seq_packet_socket(io_service&) constructor.

Move-construct a basic_seq_packet_socket from a socket of another protocol type.

template<
    typename Protocol1,
    typename SeqPacketSocketService1>
basic_seq_packet_socket(
    basic_seq_packet_socket< Protocol1, SeqPacketSocketService1 > && other,
    typename enable_if< is_convertible< Protocol1, Protocol >::value >::type *  = 0);

This constructor moves a sequenced packet socket from one object to another.

Parameters

other

The other basic_seq_packet_socket object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_seq_packet_socket(io_service&) constructor.

Bind the socket to the given local endpoint.

void bind(
    const endpoint_type & endpoint);
  » more...

boost::system::error_code bind(
    const endpoint_type & endpoint,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Bind the socket to the given local endpoint.

void bind(
    const endpoint_type & endpoint);

This function binds the socket to the specified endpoint on the local machine.

Parameters

endpoint

An endpoint on the local machine to which the socket will be bound.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::socket socket(io_service);
socket.open(boost::asio::ip::tcp::v4());
socket.bind(boost::asio::ip::tcp::endpoint(
      boost::asio::ip::tcp::v4(), 12345));

Inherited from basic_socket.

Bind the socket to the given local endpoint.

boost::system::error_code bind(
    const endpoint_type & endpoint,
    boost::system::error_code & ec);

This function binds the socket to the specified endpoint on the local machine.

Parameters

endpoint

An endpoint on the local machine to which the socket will be bound.

ec

Set to indicate what error occurred, if any.

Example
boost::asio::ip::tcp::socket socket(io_service);
socket.open(boost::asio::ip::tcp::v4());
boost::system::error_code ec;
socket.bind(boost::asio::ip::tcp::endpoint(
      boost::asio::ip::tcp::v4(), 12345), ec);
if (ec)
{
  // An error occurred.
}

Inherited from socket_base.

Socket option to permit sending of broadcast messages.

typedef implementation_defined broadcast;

Implements the SOL_SOCKET/SO_BROADCAST socket option.

Examples

Setting the option:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::broadcast option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::broadcast option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_seq_packet_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

IO control command to get the amount of data that can be read without blocking.

typedef implementation_defined bytes_readable;

Implements the FIONREAD IO control command.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::bytes_readable command(true);
socket.io_control(command);
std::size_t bytes_readable = command.get();
Requirements

Header: boost/asio/basic_seq_packet_socket.hpp

Convenience header: boost/asio.hpp

Cancel all asynchronous operations associated with the socket.

void cancel();
  » more...

boost::system::error_code cancel(
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Cancel all asynchronous operations associated with the socket.

void cancel();

This function causes all outstanding asynchronous connect, send and receive operations to finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Calls to cancel() will always fail with boost::asio::error::operation_not_supported when run on Windows XP, Windows Server 2003, and earlier versions of Windows, unless BOOST_ASIO_ENABLE_CANCELIO is defined. However, the CancelIo function has two issues that should be considered before enabling its use:

  • It will only cancel asynchronous operations that were initiated in the current thread.
  • It can appear to complete without error, but the request to cancel the unfinished operations may be silently ignored by the operating system. Whether it works or not seems to depend on the drivers that are installed.

For portable cancellation, consider using one of the following alternatives:

  • Disable asio's I/O completion port backend by defining BOOST_ASIO_DISABLE_IOCP.
  • Use the close() function to simultaneously cancel the outstanding operations and close the socket.

When running on Windows Vista, Windows Server 2008, and later, the CancelIoEx function is always used. This function does not have the problems described above.

Inherited from basic_socket.

Cancel all asynchronous operations associated with the socket.

boost::system::error_code cancel(
    boost::system::error_code & ec);

This function causes all outstanding asynchronous connect, send and receive operations to finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error.

Parameters

ec

Set to indicate what error occurred, if any.

Remarks

Calls to cancel() will always fail with boost::asio::error::operation_not_supported when run on Windows XP, Windows Server 2003, and earlier versions of Windows, unless BOOST_ASIO_ENABLE_CANCELIO is defined. However, the CancelIo function has two issues that should be considered before enabling its use:

  • It will only cancel asynchronous operations that were initiated in the current thread.
  • It can appear to complete without error, but the request to cancel the unfinished operations may be silently ignored by the operating system. Whether it works or not seems to depend on the drivers that are installed.

For portable cancellation, consider using one of the following alternatives:

  • Disable asio's I/O completion port backend by defining BOOST_ASIO_DISABLE_IOCP.
  • Use the close() function to simultaneously cancel the outstanding operations and close the socket.

When running on Windows Vista, Windows Server 2008, and later, the CancelIoEx function is always used. This function does not have the problems described above.

Close the socket.

void close();
  » more...

boost::system::error_code close(
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Close the socket.

void close();

This function is used to close the socket. Any asynchronous send, receive or connect operations will be cancelled immediately, and will complete with the boost::asio::error::operation_aborted error.

Exceptions

boost::system::system_error

Thrown on failure. Note that, even if the function indicates an error, the underlying descriptor is closed.

Remarks

For portable behaviour with respect to graceful closure of a connected socket, call shutdown() before closing the socket.

Inherited from basic_socket.

Close the socket.

boost::system::error_code close(
    boost::system::error_code & ec);

This function is used to close the socket. Any asynchronous send, receive or connect operations will be cancelled immediately, and will complete with the boost::asio::error::operation_aborted error.

Parameters

ec

Set to indicate what error occurred, if any. Note that, even if the function indicates an error, the underlying descriptor is closed.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::system::error_code ec;
socket.close(ec);
if (ec)
{
  // An error occurred.
}
Remarks

For portable behaviour with respect to graceful closure of a connected socket, call shutdown() before closing the socket.

Connect the socket to the specified endpoint.

void connect(
    const endpoint_type & peer_endpoint);
  » more...

boost::system::error_code connect(
    const endpoint_type & peer_endpoint,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Connect the socket to the specified endpoint.

void connect(
    const endpoint_type & peer_endpoint);

This function is used to connect a socket to the specified remote endpoint. The function call will block until the connection is successfully made or an error occurs.

The socket is automatically opened if it is not already open. If the connect fails, and the socket was automatically opened, the socket is not returned to the closed state.

Parameters

peer_endpoint

The remote endpoint to which the socket will be connected.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::socket socket(io_service);
boost::asio::ip::tcp::endpoint endpoint(
    boost::asio::ip::address::from_string("1.2.3.4"), 12345);
socket.connect(endpoint);

Inherited from basic_socket.

Connect the socket to the specified endpoint.

boost::system::error_code connect(
    const endpoint_type & peer_endpoint,
    boost::system::error_code & ec);

This function is used to connect a socket to the specified remote endpoint. The function call will block until the connection is successfully made or an error occurs.

The socket is automatically opened if it is not already open. If the connect fails, and the socket was automatically opened, the socket is not returned to the closed state.

Parameters

peer_endpoint

The remote endpoint to which the socket will be connected.

ec

Set to indicate what error occurred, if any.

Example
boost::asio::ip::tcp::socket socket(io_service);
boost::asio::ip::tcp::endpoint endpoint(
    boost::asio::ip::address::from_string("1.2.3.4"), 12345);
boost::system::error_code ec;
socket.connect(endpoint, ec);
if (ec)
{
  // An error occurred.
}

Inherited from socket_base.

Socket option to enable socket-level debugging.

typedef implementation_defined debug;

Implements the SOL_SOCKET/SO_DEBUG socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::debug option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::debug option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_seq_packet_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option to prevent routing, use local interfaces only.

typedef implementation_defined do_not_route;

Implements the SOL_SOCKET/SO_DONTROUTE socket option.

Examples

Setting the option:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::do_not_route option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::do_not_route option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_seq_packet_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option to report aborted connections on accept.

typedef implementation_defined enable_connection_aborted;

Implements a custom socket option that determines whether or not an accept operation is permitted to fail with boost::asio::error::connection_aborted. By default the option is false.

Examples

Setting the option:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::enable_connection_aborted option(true);
acceptor.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::enable_connection_aborted option;
acceptor.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_seq_packet_socket.hpp

Convenience header: boost/asio.hpp

The endpoint type.

typedef Protocol::endpoint endpoint_type;
Requirements

Header: boost/asio/basic_seq_packet_socket.hpp

Convenience header: boost/asio.hpp

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();
  » more...

const implementation_type & get_implementation() const;
  » more...

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

const implementation_type & get_implementation() const;

Inherited from basic_io_object.

Get the io_service associated with the object.

boost::asio::io_service & get_io_service();

This function may be used to obtain the io_service object that the I/O object uses to dispatch handlers for asynchronous operations.

Return Value

A reference to the io_service object that the I/O object will use to dispatch handlers. Ownership is not transferred to the caller.

Get an option from the socket.

void get_option(
    GettableSocketOption & option) const;
  » more...

boost::system::error_code get_option(
    GettableSocketOption & option,
    boost::system::error_code & ec) const;
  » more...

Inherited from basic_socket.

Get an option from the socket.

template<
    typename GettableSocketOption>
void get_option(
    GettableSocketOption & option) const;

This function is used to get the current value of an option on the socket.

Parameters

option

The option value to be obtained from the socket.

Exceptions

boost::system::system_error

Thrown on failure.

Example

Getting the value of the SOL_SOCKET/SO_KEEPALIVE option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::socket::keep_alive option;
socket.get_option(option);
bool is_set = option.value();

Inherited from basic_socket.

Get an option from the socket.

template<
    typename GettableSocketOption>
boost::system::error_code get_option(
    GettableSocketOption & option,
    boost::system::error_code & ec) const;

This function is used to get the current value of an option on the socket.

Parameters

option

The option value to be obtained from the socket.

ec

Set to indicate what error occurred, if any.

Example

Getting the value of the SOL_SOCKET/SO_KEEPALIVE option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::socket::keep_alive option;
boost::system::error_code ec;
socket.get_option(option, ec);
if (ec)
{
  // An error occurred.
}
bool is_set = option.value();

Get the service associated with the I/O object.

service_type & get_service();
  » more...

const service_type & get_service() const;
  » more...

Inherited from basic_io_object.

Get the service associated with the I/O object.

service_type & get_service();

Inherited from basic_io_object.

Get the service associated with the I/O object.

const service_type & get_service() const;

Inherited from basic_io_object.

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

implementation_type implementation;

Inherited from basic_io_object.

The underlying implementation type of I/O object.

typedef service_type::implementation_type implementation_type;
Requirements

Header: boost/asio/basic_seq_packet_socket.hpp

Convenience header: boost/asio.hpp

Perform an IO control command on the socket.

void io_control(
    IoControlCommand & command);
  » more...

boost::system::error_code io_control(
    IoControlCommand & command,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Perform an IO control command on the socket.

template<
    typename IoControlCommand>
void io_control(
    IoControlCommand & command);

This function is used to execute an IO control command on the socket.

Parameters

command

The IO control command to be performed on the socket.

Exceptions

boost::system::system_error

Thrown on failure.

Example

Getting the number of bytes ready to read:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::socket::bytes_readable command;
socket.io_control(command);
std::size_t bytes_readable = command.get();

Inherited from basic_socket.

Perform an IO control command on the socket.

template<
    typename IoControlCommand>
boost::system::error_code io_control(
    IoControlCommand & command,
    boost::system::error_code & ec);

This function is used to execute an IO control command on the socket.

Parameters

command

The IO control command to be performed on the socket.

ec

Set to indicate what error occurred, if any.

Example

Getting the number of bytes ready to read:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::socket::bytes_readable command;
boost::system::error_code ec;
socket.io_control(command, ec);
if (ec)
{
  // An error occurred.
}
std::size_t bytes_readable = command.get();

Inherited from basic_socket.

Determine whether the socket is open.

bool is_open() const;

Inherited from socket_base.

Socket option to send keep-alives.

typedef implementation_defined keep_alive;

Implements the SOL_SOCKET/SO_KEEPALIVE socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::keep_alive option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::keep_alive option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_seq_packet_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

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.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::linger option(true, 30);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::linger option;
socket.get_option(option);
bool is_set = option.enabled();
unsigned short timeout = option.timeout();
Requirements

Header: boost/asio/basic_seq_packet_socket.hpp

Convenience header: boost/asio.hpp

Get the local endpoint of the socket.

endpoint_type local_endpoint() const;
  » more...

endpoint_type local_endpoint(
    boost::system::error_code & ec) const;
  » more...

Inherited from basic_socket.

Get the local endpoint of the socket.

endpoint_type local_endpoint() const;

This function is used to obtain the locally bound endpoint of the socket.

Return Value

An object that represents the local endpoint of the socket.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::endpoint endpoint = socket.local_endpoint();

Inherited from basic_socket.

Get the local endpoint of the socket.

endpoint_type local_endpoint(
    boost::system::error_code & ec) const;

This function is used to obtain the locally bound endpoint of the socket.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

An object that represents the local endpoint of the socket. Returns a default-constructed endpoint object if an error occurred.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::system::error_code ec;
boost::asio::ip::tcp::endpoint endpoint = socket.local_endpoint(ec);
if (ec)
{
  // An error occurred.
}

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();
  » more...

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;
  » more...

Inherited from basic_socket.

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();

This function returns a reference to the lowest layer in a stack of layers. Since a basic_socket cannot contain any further layers, it simply returns a reference to itself.

Return Value

A reference to the lowest layer in the stack of layers. Ownership is not transferred to the caller.

Inherited from basic_socket.

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;

This function returns a const reference to the lowest layer in a stack of layers. Since a basic_socket cannot contain any further layers, it simply returns a reference to itself.

Return Value

A const reference to the lowest layer in the stack of layers. Ownership is not transferred to the caller.

Inherited from basic_socket.

A basic_socket is always the lowest layer.

typedef basic_socket< Protocol, SeqPacketSocketService > lowest_layer_type;
Types

Name

Description

broadcast

Socket option to permit sending of broadcast messages.

bytes_readable

IO control command to get the amount of data that can be read without blocking.

debug

Socket option to enable socket-level debugging.

do_not_route

Socket option to prevent routing, use local interfaces only.

enable_connection_aborted

Socket option to report aborted connections on accept.

endpoint_type

The endpoint type.

implementation_type

The underlying implementation type of I/O object.

keep_alive

Socket option to send keep-alives.

linger

Socket option to specify whether the socket lingers on close if unsent data is present.

lowest_layer_type

A basic_socket is always the lowest layer.

message_flags

Bitmask type for flags that can be passed to send and receive operations.

native_handle_type

The native representation of a socket.

native_type

(Deprecated: Use native_handle_type.) The native representation of a socket.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

protocol_type

The protocol type.

receive_buffer_size

Socket option for the receive buffer size of a socket.

receive_low_watermark

Socket option for the receive low watermark.

reuse_address

Socket option to allow the socket to be bound to an address that is already in use.

send_buffer_size

Socket option for the send buffer size of a socket.

send_low_watermark

Socket option for the send low watermark.

service_type

The type of the service that will be used to provide I/O operations.

shutdown_type

Different ways a socket may be shutdown.

Member Functions

Name

Description

assign

Assign an existing native socket to the socket.

async_connect

Start an asynchronous connect.

at_mark

Determine whether the socket is at the out-of-band data mark.

available

Determine the number of bytes available for reading.

basic_socket

Construct a basic_socket without opening it.

Construct and open a basic_socket.

Construct a basic_socket, opening it and binding it to the given local endpoint.

Construct a basic_socket on an existing native socket.

Move-construct a basic_socket from another.

Move-construct a basic_socket from a socket of another protocol type.

bind

Bind the socket to the given local endpoint.

cancel

Cancel all asynchronous operations associated with the socket.

close

Close the socket.

connect

Connect the socket to the specified endpoint.

get_io_service

Get the io_service associated with the object.

get_option

Get an option from the socket.

io_control

Perform an IO control command on the socket.

is_open

Determine whether the socket is open.

local_endpoint

Get the local endpoint of the socket.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native socket representation.

native_handle

Get the native socket representation.

native_non_blocking

Gets the non-blocking mode of the native socket implementation.

Sets the non-blocking mode of the native socket implementation.

non_blocking

Gets the non-blocking mode of the socket.

Sets the non-blocking mode of the socket.

open

Open the socket using the specified protocol.

operator=

Move-assign a basic_socket from another.

Move-assign a basic_socket from a socket of another protocol type.

remote_endpoint

Get the remote endpoint of the socket.

set_option

Set an option on the socket.

shutdown

Disable sends or receives on the socket.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

~basic_socket

Protected destructor to prevent deletion through this type.

Data Members

Name

Description

max_connections

The maximum length of the queue of pending incoming connections.

message_do_not_route

Specify that the data should not be subject to routing.

message_end_of_record

Specifies that the data marks the end of a record.

message_out_of_band

Process out-of-band data.

message_peek

Peek at incoming data without removing it from the input queue.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_socket class template provides functionality that is common to both stream-oriented and datagram-oriented sockets.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/basic_seq_packet_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

The maximum length of the queue of pending incoming connections.

static const int max_connections = implementation_defined;

Inherited from socket_base.

Specify that the data should not be subject to routing.

static const int message_do_not_route = implementation_defined;

Inherited from socket_base.

Specifies that the data marks the end of a record.

static const int message_end_of_record = implementation_defined;

Inherited from socket_base.

Bitmask type for flags that can be passed to send and receive operations.

typedef int message_flags;
Requirements

Header: boost/asio/basic_seq_packet_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Process out-of-band data.

static const int message_out_of_band = implementation_defined;

Inherited from socket_base.

Peek at incoming data without removing it from the input queue.

static const int message_peek = implementation_defined;

Inherited from basic_socket.

(Deprecated: Use native_handle().) Get the native socket representation.

native_type native();

This function may be used to obtain the underlying representation of the socket. This is intended to allow access to native socket functionality that is not otherwise provided.

Inherited from basic_socket.

Get the native socket representation.

native_handle_type native_handle();

This function may be used to obtain the underlying representation of the socket. This is intended to allow access to native socket functionality that is not otherwise provided.

The native representation of a socket.

typedef SeqPacketSocketService::native_handle_type native_handle_type;
Requirements

Header: boost/asio/basic_seq_packet_socket.hpp

Convenience header: boost/asio.hpp

Gets the non-blocking mode of the native socket implementation.

bool native_non_blocking() const;
  » more...

Sets the non-blocking mode of the native socket implementation.

void native_non_blocking(
    bool mode);
  » more...

boost::system::error_code native_non_blocking(
    bool mode,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Gets the non-blocking mode of the native socket implementation.

bool native_non_blocking() const;

This function is used to retrieve the non-blocking mode of the underlying native socket. This mode has no effect on the behaviour of the socket object's synchronous operations.

Return Value

true if the underlying socket is in non-blocking mode and direct system calls may fail with boost::asio::error::would_block (or the equivalent system error).

Remarks

The current non-blocking mode is cached by the socket object. Consequently, the return value may be incorrect if the non-blocking mode was set directly on the native socket.

Example

This function is intended to allow the encapsulation of arbitrary non-blocking system calls as asynchronous operations, in a way that is transparent to the user of the socket object. The following example illustrates how Linux's sendfile system call might be encapsulated:

template <typename Handler>
struct sendfile_op
{
  tcp::socket& sock_;
  int fd_;
  Handler handler_;
  off_t offset_;
  std::size_t total_bytes_transferred_;

  // Function call operator meeting WriteHandler requirements.
  // Used as the handler for the async_write_some operation.
  void operator()(boost::system::error_code ec, std::size_t)
  {
    // Put the underlying socket into non-blocking mode.
    if (!ec)
      if (!sock_.native_non_blocking())
        sock_.native_non_blocking(true, ec);

    if (!ec)
    {
      for (;;)
      {
        // Try the system call.
        errno = 0;
        int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536);
        ec = boost::system::error_code(n < 0 ? errno : 0,
            boost::asio::error::get_system_category());
        total_bytes_transferred_ += ec ? 0 : n;

        // Retry operation immediately if interrupted by signal.
        if (ec == boost::asio::error::interrupted)
          continue;

        // Check if we need to run the operation again.
        if (ec == boost::asio::error::would_block
            || ec == boost::asio::error::try_again)
        {
          // We have to wait for the socket to become ready again.
          sock_.async_write_some(boost::asio::null_buffers(), *this);
          return;
        }

        if (ec || n == 0)
        {
          // An error occurred, or we have reached the end of the file.
          // Either way we must exit the loop so we can call the handler.
          break;
        }

        // Loop around to try calling sendfile again.
      }
    }

    // Pass result back to user's handler.
    handler_(ec, total_bytes_transferred_);
  }
};

template <typename Handler>
void async_sendfile(tcp::socket& sock, int fd, Handler h)
{
  sendfile_op<Handler> op = { sock, fd, h, 0, 0 };
  sock.async_write_some(boost::asio::null_buffers(), op);
}

Inherited from basic_socket.

Sets the non-blocking mode of the native socket implementation.

void native_non_blocking(
    bool mode);

This function is used to modify the non-blocking mode of the underlying native socket. It has no effect on the behaviour of the socket object's synchronous operations.

Parameters

mode

If true, the underlying socket is put into non-blocking mode and direct system calls may fail with boost::asio::error::would_block (or the equivalent system error).

Exceptions

boost::system::system_error

Thrown on failure. If the mode is false, but the current value of non_blocking() is true, this function fails with boost::asio::error::invalid_argument, as the combination does not make sense.

Example

This function is intended to allow the encapsulation of arbitrary non-blocking system calls as asynchronous operations, in a way that is transparent to the user of the socket object. The following example illustrates how Linux's sendfile system call might be encapsulated:

template <typename Handler>
struct sendfile_op
{
  tcp::socket& sock_;
  int fd_;
  Handler handler_;
  off_t offset_;
  std::size_t total_bytes_transferred_;

  // Function call operator meeting WriteHandler requirements.
  // Used as the handler for the async_write_some operation.
  void operator()(boost::system::error_code ec, std::size_t)
  {
    // Put the underlying socket into non-blocking mode.
    if (!ec)
      if (!sock_.native_non_blocking())
        sock_.native_non_blocking(true, ec);

    if (!ec)
    {
      for (;;)
      {
        // Try the system call.
        errno = 0;
        int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536);
        ec = boost::system::error_code(n < 0 ? errno : 0,
            boost::asio::error::get_system_category());
        total_bytes_transferred_ += ec ? 0 : n;

        // Retry operation immediately if interrupted by signal.
        if (ec == boost::asio::error::interrupted)
          continue;

        // Check if we need to run the operation again.
        if (ec == boost::asio::error::would_block
            || ec == boost::asio::error::try_again)
        {
          // We have to wait for the socket to become ready again.
          sock_.async_write_some(boost::asio::null_buffers(), *this);
          return;
        }

        if (ec || n == 0)
        {
          // An error occurred, or we have reached the end of the file.
          // Either way we must exit the loop so we can call the handler.
          break;
        }

        // Loop around to try calling sendfile again.
      }
    }

    // Pass result back to user's handler.
    handler_(ec, total_bytes_transferred_);
  }
};

template <typename Handler>
void async_sendfile(tcp::socket& sock, int fd, Handler h)
{
  sendfile_op<Handler> op = { sock, fd, h, 0, 0 };
  sock.async_write_some(boost::asio::null_buffers(), op);
}

Inherited from basic_socket.

Sets the non-blocking mode of the native socket implementation.

boost::system::error_code native_non_blocking(
    bool mode,
    boost::system::error_code & ec);

This function is used to modify the non-blocking mode of the underlying native socket. It has no effect on the behaviour of the socket object's synchronous operations.

Parameters

mode

If true, the underlying socket is put into non-blocking mode and direct system calls may fail with boost::asio::error::would_block (or the equivalent system error).

ec

Set to indicate what error occurred, if any. If the mode is false, but the current value of non_blocking() is true, this function fails with boost::asio::error::invalid_argument, as the combination does not make sense.

Example

This function is intended to allow the encapsulation of arbitrary non-blocking system calls as asynchronous operations, in a way that is transparent to the user of the socket object. The following example illustrates how Linux's sendfile system call might be encapsulated:

template <typename Handler>
struct sendfile_op
{
  tcp::socket& sock_;
  int fd_;
  Handler handler_;
  off_t offset_;
  std::size_t total_bytes_transferred_;

  // Function call operator meeting WriteHandler requirements.
  // Used as the handler for the async_write_some operation.
  void operator()(boost::system::error_code ec, std::size_t)
  {
    // Put the underlying socket into non-blocking mode.
    if (!ec)
      if (!sock_.native_non_blocking())
        sock_.native_non_blocking(true, ec);

    if (!ec)
    {
      for (;;)
      {
        // Try the system call.
        errno = 0;
        int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536);
        ec = boost::system::error_code(n < 0 ? errno : 0,
            boost::asio::error::get_system_category());
        total_bytes_transferred_ += ec ? 0 : n;

        // Retry operation immediately if interrupted by signal.
        if (ec == boost::asio::error::interrupted)
          continue;

        // Check if we need to run the operation again.
        if (ec == boost::asio::error::would_block
            || ec == boost::asio::error::try_again)
        {
          // We have to wait for the socket to become ready again.
          sock_.async_write_some(boost::asio::null_buffers(), *this);
          return;
        }

        if (ec || n == 0)
        {
          // An error occurred, or we have reached the end of the file.
          // Either way we must exit the loop so we can call the handler.
          break;
        }

        // Loop around to try calling sendfile again.
      }
    }

    // Pass result back to user's handler.
    handler_(ec, total_bytes_transferred_);
  }
};

template <typename Handler>
void async_sendfile(tcp::socket& sock, int fd, Handler h)
{
  sendfile_op<Handler> op = { sock, fd, h, 0, 0 };
  sock.async_write_some(boost::asio::null_buffers(), op);
}

(Deprecated: Use native_handle_type.) The native representation of a socket.

typedef SeqPacketSocketService::native_handle_type native_type;
Requirements

Header: boost/asio/basic_seq_packet_socket.hpp

Convenience header: boost/asio.hpp

Gets the non-blocking mode of the socket.

bool non_blocking() const;
  » more...

Sets the non-blocking mode of the socket.

void non_blocking(
    bool mode);
  » more...

boost::system::error_code non_blocking(
    bool mode,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Gets the non-blocking mode of the socket.

bool non_blocking() const;
Return Value

true if the socket's synchronous operations will fail with boost::asio::error::would_block if they are unable to perform the requested operation immediately. If false, synchronous operations will block until complete.

Remarks

The non-blocking mode has no effect on the behaviour of asynchronous operations. Asynchronous operations will never fail with the error boost::asio::error::would_block.

Inherited from basic_socket.

Sets the non-blocking mode of the socket.

void non_blocking(
    bool mode);
Parameters

mode

If true, the socket's synchronous operations will fail with boost::asio::error::would_block if they are unable to perform the requested operation immediately. If false, synchronous operations will block until complete.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

The non-blocking mode has no effect on the behaviour of asynchronous operations. Asynchronous operations will never fail with the error boost::asio::error::would_block.

Inherited from basic_socket.

Sets the non-blocking mode of the socket.

boost::system::error_code non_blocking(
    bool mode,
    boost::system::error_code & ec);
Parameters

mode

If true, the socket's synchronous operations will fail with boost::asio::error::would_block if they are unable to perform the requested operation immediately. If false, synchronous operations will block until complete.

ec

Set to indicate what error occurred, if any.

Remarks

The non-blocking mode has no effect on the behaviour of asynchronous operations. Asynchronous operations will never fail with the error boost::asio::error::would_block.

Inherited from socket_base.

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

typedef implementation_defined non_blocking_io;

Implements the FIONBIO IO control command.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::non_blocking_io command(true);
socket.io_control(command);
Requirements

Header: boost/asio/basic_seq_packet_socket.hpp

Convenience header: boost/asio.hpp

Open the socket using the specified protocol.

void open(
    const protocol_type & protocol = protocol_type());
  » more...

boost::system::error_code open(
    const protocol_type & protocol,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Open the socket using the specified protocol.

void open(
    const protocol_type & protocol = protocol_type());

This function opens the socket so that it will use the specified protocol.

Parameters

protocol

An object specifying protocol parameters to be used.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::socket socket(io_service);
socket.open(boost::asio::ip::tcp::v4());

Inherited from basic_socket.

Open the socket using the specified protocol.

boost::system::error_code open(
    const protocol_type & protocol,
    boost::system::error_code & ec);

This function opens the socket so that it will use the specified protocol.

Parameters

protocol

An object specifying which protocol is to be used.

ec

Set to indicate what error occurred, if any.

Example
boost::asio::ip::tcp::socket socket(io_service);
boost::system::error_code ec;
socket.open(boost::asio::ip::tcp::v4(), ec);
if (ec)
{
  // An error occurred.
}

Move-assign a basic_seq_packet_socket from another.

basic_seq_packet_socket & operator=(
    basic_seq_packet_socket && other);
  » more...

Move-assign a basic_seq_packet_socket from a socket of another protocol type.

template<
    typename Protocol1,
    typename SeqPacketSocketService1>
enable_if< is_convertible< Protocol1, Protocol >::value, basic_seq_packet_socket >::type & operator=(
    basic_seq_packet_socket< Protocol1, SeqPacketSocketService1 > && other);
  » more...

Move-assign a basic_seq_packet_socket from another.

basic_seq_packet_socket & operator=(
    basic_seq_packet_socket && other);

This assignment operator moves a sequenced packet socket from one object to another.

Parameters

other

The other basic_seq_packet_socket object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_seq_packet_socket(io_service&) constructor.

Move-assign a basic_seq_packet_socket from a socket of another protocol type.

template<
    typename Protocol1,
    typename SeqPacketSocketService1>
enable_if< is_convertible< Protocol1, Protocol >::value, basic_seq_packet_socket >::type & operator=(
    basic_seq_packet_socket< Protocol1, SeqPacketSocketService1 > && other);

This assignment operator moves a sequenced packet socket from one object to another.

Parameters

other

The other basic_seq_packet_socket object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_seq_packet_socket(io_service&) constructor.

The protocol type.

typedef Protocol protocol_type;
Requirements

Header: boost/asio/basic_seq_packet_socket.hpp

Convenience header: boost/asio.hpp

Receive some data on the socket.

template<
    typename MutableBufferSequence>
std::size_t receive(
    const MutableBufferSequence & buffers,
    socket_base::message_flags & out_flags);
  » more...

template<
    typename MutableBufferSequence>
std::size_t receive(
    const MutableBufferSequence & buffers,
    socket_base::message_flags in_flags,
    socket_base::message_flags & out_flags);
  » more...

Receive some data on a connected socket.

template<
    typename MutableBufferSequence>
std::size_t receive(
    const MutableBufferSequence & buffers,
    socket_base::message_flags in_flags,
    socket_base::message_flags & out_flags,
    boost::system::error_code & ec);
  » more...

Receive some data on the socket.

template<
    typename MutableBufferSequence>
std::size_t receive(
    const MutableBufferSequence & buffers,
    socket_base::message_flags & out_flags);

This function is used to receive data on the sequenced packet socket. The function call will block until data has been received successfully, or until an error occurs.

Parameters

buffers

One or more buffers into which the data will be received.

out_flags

After the receive call completes, contains flags associated with the received data. For example, if the socket_base::message_end_of_record bit is set then the received data marks the end of a record.

Return Value

The number of bytes received.

Exceptions

boost::system::system_error

Thrown on failure. An error code of boost::asio::error::eof indicates that the connection was closed by the peer.

Example

To receive into a single data buffer use the buffer function as follows:

socket.receive(boost::asio::buffer(data, size), out_flags);

See the buffer documentation for information on receiving into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Receive some data on the socket.

template<
    typename MutableBufferSequence>
std::size_t receive(
    const MutableBufferSequence & buffers,
    socket_base::message_flags in_flags,
    socket_base::message_flags & out_flags);

This function is used to receive data on the sequenced packet socket. The function call will block until data has been received successfully, or until an error occurs.

Parameters

buffers

One or more buffers into which the data will be received.

in_flags

Flags specifying how the receive call is to be made.

out_flags

After the receive call completes, contains flags associated with the received data. For example, if the socket_base::message_end_of_record bit is set then the received data marks the end of a record.

Return Value

The number of bytes received.

Exceptions

boost::system::system_error

Thrown on failure. An error code of boost::asio::error::eof indicates that the connection was closed by the peer.

Remarks

The receive operation may not receive all of the requested number of bytes. Consider using the read function if you need to ensure that the requested amount of data is read before the blocking operation completes.

Example

To receive into a single data buffer use the buffer function as follows:

socket.receive(boost::asio::buffer(data, size), 0, out_flags);

See the buffer documentation for information on receiving into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Receive some data on a connected socket.

template<
    typename MutableBufferSequence>
std::size_t receive(
    const MutableBufferSequence & buffers,
    socket_base::message_flags in_flags,
    socket_base::message_flags & out_flags,
    boost::system::error_code & ec);

This function is used to receive data on the sequenced packet socket. The function call will block until data has been received successfully, or until an error occurs.

Parameters

buffers

One or more buffers into which the data will be received.

in_flags

Flags specifying how the receive call is to be made.

out_flags

After the receive call completes, contains flags associated with the received data. For example, if the socket_base::message_end_of_record bit is set then the received data marks the end of a record.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes received. Returns 0 if an error occurred.

Remarks

The receive operation may not receive all of the requested number of bytes. Consider using the read function if you need to ensure that the requested amount of data is read before the blocking operation completes.

Inherited from socket_base.

Socket option for the receive buffer size of a socket.

typedef implementation_defined receive_buffer_size;

Implements the SOL_SOCKET/SO_RCVBUF socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_buffer_size option(8192);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_buffer_size option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/basic_seq_packet_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option for the receive low watermark.

typedef implementation_defined receive_low_watermark;

Implements the SOL_SOCKET/SO_RCVLOWAT socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_low_watermark option(1024);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_low_watermark option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/basic_seq_packet_socket.hpp

Convenience header: boost/asio.hpp

Get the remote endpoint of the socket.

endpoint_type remote_endpoint() const;
  » more...

endpoint_type remote_endpoint(
    boost::system::error_code & ec) const;
  » more...

Inherited from basic_socket.

Get the remote endpoint of the socket.

endpoint_type remote_endpoint() const;

This function is used to obtain the remote endpoint of the socket.

Return Value

An object that represents the remote endpoint of the socket.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::endpoint endpoint = socket.remote_endpoint();

Inherited from basic_socket.

Get the remote endpoint of the socket.

endpoint_type remote_endpoint(
    boost::system::error_code & ec) const;

This function is used to obtain the remote endpoint of the socket.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

An object that represents the remote endpoint of the socket. Returns a default-constructed endpoint object if an error occurred.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::system::error_code ec;
boost::asio::ip::tcp::endpoint endpoint = socket.remote_endpoint(ec);
if (ec)
{
  // An error occurred.
}

Inherited from socket_base.

Socket option to allow the socket to be bound to an address that is already in use.

typedef implementation_defined reuse_address;

Implements the SOL_SOCKET/SO_REUSEADDR socket option.

Examples

Setting the option:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::reuse_address option(true);
acceptor.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::reuse_address option;
acceptor.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_seq_packet_socket.hpp

Convenience header: boost/asio.hpp

Send some data on the socket.

template<
    typename ConstBufferSequence>
std::size_t send(
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags);
  » more...

template<
    typename ConstBufferSequence>
std::size_t send(
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags,
    boost::system::error_code & ec);
  » more...

Send some data on the socket.

template<
    typename ConstBufferSequence>
std::size_t send(
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags);

This function is used to send data on the sequenced packet socket. The function call will block until the data has been sent successfully, or an until error occurs.

Parameters

buffers

One or more data buffers to be sent on the socket.

flags

Flags specifying how the send call is to be made.

Return Value

The number of bytes sent.

Exceptions

boost::system::system_error

Thrown on failure.

Example

To send a single data buffer use the buffer function as follows:

socket.send(boost::asio::buffer(data, size), 0);

See the buffer documentation for information on sending multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Send some data on the socket.

template<
    typename ConstBufferSequence>
std::size_t send(
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags,
    boost::system::error_code & ec);

This function is used to send data on the sequenced packet socket. The function call will block the data has been sent successfully, or an until error occurs.

Parameters

buffers

One or more data buffers to be sent on the socket.

flags

Flags specifying how the send call is to be made.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes sent. Returns 0 if an error occurred.

Remarks

The send operation may not transmit all of the data to the peer. Consider using the write function if you need to ensure that all data is written before the blocking operation completes.

Inherited from socket_base.

Socket option for the send buffer size of a socket.

typedef implementation_defined send_buffer_size;

Implements the SOL_SOCKET/SO_SNDBUF socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_buffer_size option(8192);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_buffer_size option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/basic_seq_packet_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option for the send low watermark.

typedef implementation_defined send_low_watermark;

Implements the SOL_SOCKET/SO_SNDLOWAT socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_low_watermark option(1024);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_low_watermark option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/basic_seq_packet_socket.hpp

Convenience header: boost/asio.hpp

Inherited from basic_io_object.

(Deprecated: Use get_service().) The service associated with the I/O object.

service_type & service;
Remarks

Available only for services that do not support movability.

Inherited from basic_io_object.

The type of the service that will be used to provide I/O operations.

typedef SeqPacketSocketService service_type;
Requirements

Header: boost/asio/basic_seq_packet_socket.hpp

Convenience header: boost/asio.hpp

Set an option on the socket.

void set_option(
    const SettableSocketOption & option);
  » more...

boost::system::error_code set_option(
    const SettableSocketOption & option,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

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.

Parameters

option

The new option value to be set on the socket.

Exceptions

boost::system::system_error

Thrown on failure.

Example

Setting the IPPROTO_TCP/TCP_NODELAY option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::no_delay option(true);
socket.set_option(option);

Inherited from basic_socket.

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.

Parameters

option

The new option value to be set on the socket.

ec

Set to indicate what error occurred, if any.

Example

Setting the IPPROTO_TCP/TCP_NODELAY option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::no_delay option(true);
boost::system::error_code ec;
socket.set_option(option, ec);
if (ec)
{
  // An error occurred.
}

Disable sends or receives on the socket.

void shutdown(
    shutdown_type what);
  » more...

boost::system::error_code shutdown(
    shutdown_type what,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Disable sends or receives on the socket.

void shutdown(
    shutdown_type what);

This function is used to disable send operations, receive operations, or both.

Parameters

what

Determines what types of operation will no longer be allowed.

Exceptions

boost::system::system_error

Thrown on failure.

Example

Shutting down the send side of the socket:

boost::asio::ip::tcp::socket socket(io_service);
...
socket.shutdown(boost::asio::ip::tcp::socket::shutdown_send);

Inherited from basic_socket.

Disable sends or receives on the socket.

boost::system::error_code shutdown(
    shutdown_type what,
    boost::system::error_code & ec);

This function is used to disable send operations, receive operations, or both.

Parameters

what

Determines what types of operation will no longer be allowed.

ec

Set to indicate what error occurred, if any.

Example

Shutting down the send side of the socket:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::system::error_code ec;
socket.shutdown(boost::asio::ip::tcp::socket::shutdown_send, ec);
if (ec)
{
  // An error occurred.
}

Inherited from socket_base.

Different ways a socket may be shutdown.

enum shutdown_type

Values

shutdown_receive

Shutdown the receive side of the socket.

shutdown_send

Shutdown the send side of the socket.

shutdown_both

Shutdown both send and receive on the socket.

Provides serial port functionality.

template<
    typename SerialPortService = serial_port_service>
class basic_serial_port :
  public basic_io_object< SerialPortService >,
  public serial_port_base
Types

Name

Description

implementation_type

The underlying implementation type of I/O object.

lowest_layer_type

A basic_serial_port is always the lowest layer.

native_handle_type

The native representation of a serial port.

native_type

(Deprecated: Use native_handle_type.) The native representation of a serial port.

service_type

The type of the service that will be used to provide I/O operations.

Member Functions

Name

Description

assign

Assign an existing native serial port to the serial port.

async_read_some

Start an asynchronous read.

async_write_some

Start an asynchronous write.

basic_serial_port

Construct a basic_serial_port without opening it.

Construct and open a basic_serial_port.

Construct a basic_serial_port on an existing native serial port.

Move-construct a basic_serial_port from another.

cancel

Cancel all asynchronous operations associated with the serial port.

close

Close the serial port.

get_io_service

Get the io_service associated with the object.

get_option

Get an option from the serial port.

is_open

Determine whether the serial port is open.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native serial port representation.

native_handle

Get the native serial port representation.

open

Open the serial port using the specified device name.

operator=

Move-assign a basic_serial_port from another.

read_some

Read some data from the serial port.

send_break

Send a break sequence to the serial port.

set_option

Set an option on the serial port.

write_some

Write some data to the serial port.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_serial_port class template provides functionality that is common to all serial ports.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/basic_serial_port.hpp

Convenience header: boost/asio.hpp

Assign an existing native serial port to the serial port.

void assign(
    const native_handle_type & native_serial_port);
  » more...

boost::system::error_code assign(
    const native_handle_type & native_serial_port,
    boost::system::error_code & ec);
  » more...

Assign an existing native serial port to the serial port.

void assign(
    const native_handle_type & native_serial_port);

Assign an existing native serial port to the serial port.

boost::system::error_code assign(
    const native_handle_type & native_serial_port,
    boost::system::error_code & ec);

Start an asynchronous read.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_read_some(
    const MutableBufferSequence & buffers,
    ReadHandler handler);

This function is used to asynchronously read data from the serial port. The function call always returns immediately.

Parameters

buffers

One or more buffers into which the data will be read. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

handler

The handler to be called when the read operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes read.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

The read operation may not read all of the requested number of bytes. Consider using the async_read function if you need to ensure that the requested amount of data is read before the asynchronous operation completes.

Example

To read into a single data buffer use the buffer function as follows:

serial_port.async_read_some(boost::asio::buffer(data, size), handler);

See the buffer documentation for information on reading into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Start an asynchronous write.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_write_some(
    const ConstBufferSequence & buffers,
    WriteHandler handler);

This function is used to asynchronously write data to the serial port. The function call always returns immediately.

Parameters

buffers

One or more data buffers to be written to the serial port. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

handler

The handler to be called when the write operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes written.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

The write operation may not transmit all of the data to the peer. Consider using the async_write function if you need to ensure that all data is written before the asynchronous operation completes.

Example

To write a single data buffer use the buffer function as follows:

serial_port.async_write_some(boost::asio::buffer(data, size), handler);

See the buffer documentation for information on writing multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Construct a basic_serial_port without opening it.

explicit basic_serial_port(
    boost::asio::io_service & io_service);
  » more...

Construct and open a basic_serial_port.

explicit basic_serial_port(
    boost::asio::io_service & io_service,
    const char * device);
  » more...

explicit basic_serial_port(
    boost::asio::io_service & io_service,
    const std::string & device);
  » more...

Construct a basic_serial_port on an existing native serial port.

basic_serial_port(
    boost::asio::io_service & io_service,
    const native_handle_type & native_serial_port);
  » more...

Move-construct a basic_serial_port from another.

basic_serial_port(
    basic_serial_port && other);
  » more...

Construct a basic_serial_port without opening it.

basic_serial_port(
    boost::asio::io_service & io_service);

This constructor creates a serial port without opening it.

Parameters

io_service

The io_service object that the serial port will use to dispatch handlers for any asynchronous operations performed on the port.

Construct and open a basic_serial_port.

basic_serial_port(
    boost::asio::io_service & io_service,
    const char * device);

This constructor creates and opens a serial port for the specified device name.

Parameters

io_service

The io_service object that the serial port will use to dispatch handlers for any asynchronous operations performed on the port.

device

The platform-specific device name for this serial port.

Construct and open a basic_serial_port.

basic_serial_port(
    boost::asio::io_service & io_service,
    const std::string & device);

This constructor creates and opens a serial port for the specified device name.

Parameters

io_service

The io_service object that the serial port will use to dispatch handlers for any asynchronous operations performed on the port.

device

The platform-specific device name for this serial port.

Construct a basic_serial_port on an existing native serial port.

basic_serial_port(
    boost::asio::io_service & io_service,
    const native_handle_type & native_serial_port);

This constructor creates a serial port object to hold an existing native serial port.

Parameters

io_service

The io_service object that the serial port will use to dispatch handlers for any asynchronous operations performed on the port.

native_serial_port

A native serial port.

Exceptions

boost::system::system_error

Thrown on failure.

Move-construct a basic_serial_port from another.

basic_serial_port(
    basic_serial_port && other);

This constructor moves a serial port from one object to another.

Parameters

other

The other basic_serial_port object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_serial_port(io_service&) constructor.

Cancel all asynchronous operations associated with the serial port.

void cancel();
  » more...

boost::system::error_code cancel(
    boost::system::error_code & ec);
  » more...

Cancel all asynchronous operations associated with the serial port.

void cancel();

This function causes all outstanding asynchronous read or write operations to finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error.

Exceptions

boost::system::system_error

Thrown on failure.

Cancel all asynchronous operations associated with the serial port.

boost::system::error_code cancel(
    boost::system::error_code & ec);

This function causes all outstanding asynchronous read or write operations to finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error.

Parameters

ec

Set to indicate what error occurred, if any.

Close the serial port.

void close();
  » more...

boost::system::error_code close(
    boost::system::error_code & ec);
  » more...

Close the serial port.

void close();

This function is used to close the serial port. Any asynchronous read or write operations will be cancelled immediately, and will complete with the boost::asio::error::operation_aborted error.

Exceptions

boost::system::system_error

Thrown on failure.

Close the serial port.

boost::system::error_code close(
    boost::system::error_code & ec);

This function is used to close the serial port. Any asynchronous read or write operations will be cancelled immediately, and will complete with the boost::asio::error::operation_aborted error.

Parameters

ec

Set to indicate what error occurred, if any.

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();
  » more...

const implementation_type & get_implementation() const;
  » more...

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

const implementation_type & get_implementation() const;

Inherited from basic_io_object.

Get the io_service associated with the object.

boost::asio::io_service & get_io_service();

This function may be used to obtain the io_service object that the I/O object uses to dispatch handlers for asynchronous operations.

Return Value

A reference to the io_service object that the I/O object will use to dispatch handlers. Ownership is not transferred to the caller.

Get an option from the serial port.

template<
    typename GettableSerialPortOption>
void get_option(
    GettableSerialPortOption & option);
  » more...

template<
    typename GettableSerialPortOption>
boost::system::error_code get_option(
    GettableSerialPortOption & option,
    boost::system::error_code & ec);
  » more...

Get an option from the serial port.

template<
    typename GettableSerialPortOption>
void get_option(
    GettableSerialPortOption & option);

This function is used to get the current value of an option on the serial port.

Parameters

option

The option value to be obtained from the serial port.

Exceptions

boost::system::system_error

Thrown on failure.

Get an option from the serial port.

template<
    typename GettableSerialPortOption>
boost::system::error_code get_option(
    GettableSerialPortOption & option,
    boost::system::error_code & ec);

This function is used to get the current value of an option on the serial port.

Parameters

option

The option value to be obtained from the serial port.

ec

Set to indicate what error occurred, if any.

Get the service associated with the I/O object.

service_type & get_service();
  » more...

const service_type & get_service() const;
  » more...

Inherited from basic_io_object.

Get the service associated with the I/O object.

service_type & get_service();

Inherited from basic_io_object.

Get the service associated with the I/O object.

const service_type & get_service() const;

Inherited from basic_io_object.

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

implementation_type implementation;

Inherited from basic_io_object.

The underlying implementation type of I/O object.

typedef service_type::implementation_type implementation_type;
Requirements

Header: boost/asio/basic_serial_port.hpp

Convenience header: boost/asio.hpp

Determine whether the serial port is open.

bool is_open() const;

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();
  » more...

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;
  » more...

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();

This function returns a reference to the lowest layer in a stack of layers. Since a basic_serial_port cannot contain any further layers, it simply returns a reference to itself.

Return Value

A reference to the lowest layer in the stack of layers. Ownership is not transferred to the caller.

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;

This function returns a const reference to the lowest layer in a stack of layers. Since a basic_serial_port cannot contain any further layers, it simply returns a reference to itself.

Return Value

A const reference to the lowest layer in the stack of layers. Ownership is not transferred to the caller.

A basic_serial_port is always the lowest layer.

typedef basic_serial_port< SerialPortService > lowest_layer_type;
Types

Name

Description

implementation_type

The underlying implementation type of I/O object.

lowest_layer_type

A basic_serial_port is always the lowest layer.

native_handle_type

The native representation of a serial port.

native_type

(Deprecated: Use native_handle_type.) The native representation of a serial port.

service_type

The type of the service that will be used to provide I/O operations.

Member Functions

Name

Description

assign

Assign an existing native serial port to the serial port.

async_read_some

Start an asynchronous read.

async_write_some

Start an asynchronous write.

basic_serial_port

Construct a basic_serial_port without opening it.

Construct and open a basic_serial_port.

Construct a basic_serial_port on an existing native serial port.

Move-construct a basic_serial_port from another.

cancel

Cancel all asynchronous operations associated with the serial port.

close

Close the serial port.

get_io_service

Get the io_service associated with the object.

get_option

Get an option from the serial port.

is_open

Determine whether the serial port is open.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native serial port representation.

native_handle

Get the native serial port representation.

open

Open the serial port using the specified device name.

operator=

Move-assign a basic_serial_port from another.

read_some

Read some data from the serial port.

send_break

Send a break sequence to the serial port.

set_option

Set an option on the serial port.

write_some

Write some data to the serial port.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_serial_port class template provides functionality that is common to all serial ports.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/basic_serial_port.hpp

Convenience header: boost/asio.hpp

(Deprecated: Use native_handle().) Get the native serial port representation.

native_type native();

This function may be used to obtain the underlying representation of the serial port. This is intended to allow access to native serial port functionality that is not otherwise provided.

Get the native serial port representation.

native_handle_type native_handle();

This function may be used to obtain the underlying representation of the serial port. This is intended to allow access to native serial port functionality that is not otherwise provided.

The native representation of a serial port.

typedef SerialPortService::native_handle_type native_handle_type;
Requirements

Header: boost/asio/basic_serial_port.hpp

Convenience header: boost/asio.hpp

(Deprecated: Use native_handle_type.) The native representation of a serial port.

typedef SerialPortService::native_handle_type native_type;
Requirements

Header: boost/asio/basic_serial_port.hpp

Convenience header: boost/asio.hpp

Open the serial port using the specified device name.

void open(
    const std::string & device);
  » more...

boost::system::error_code open(
    const std::string & device,
    boost::system::error_code & ec);
  » more...

Open the serial port using the specified device name.

void open(
    const std::string & device);

This function opens the serial port for the specified device name.

Parameters

device

The platform-specific device name.

Exceptions

boost::system::system_error

Thrown on failure.

Open the serial port using the specified device name.

boost::system::error_code open(
    const std::string & device,
    boost::system::error_code & ec);

This function opens the serial port using the given platform-specific device name.

Parameters

device

The platform-specific device name.

ec

Set the indicate what error occurred, if any.

Move-assign a basic_serial_port from another.

basic_serial_port & operator=(
    basic_serial_port && other);

This assignment operator moves a serial port from one object to another.

Parameters

other

The other basic_serial_port object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_serial_port(io_service&) constructor.

Read some data from the serial port.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers);
  » more...

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);
  » more...

Read some data from the serial port.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers);

This function is used to read data from the serial port. The function call will block until one or more bytes of data has been read successfully, or until an error occurs.

Parameters

buffers

One or more buffers into which the data will be read.

Return Value

The number of bytes read.

Exceptions

boost::system::system_error

Thrown on failure. An error code of boost::asio::error::eof indicates that the connection was closed by the peer.

Remarks

The read_some operation may not read all of the requested number of bytes. Consider using the read function if you need to ensure that the requested amount of data is read before the blocking operation completes.

Example

To read into a single data buffer use the buffer function as follows:

serial_port.read_some(boost::asio::buffer(data, size));

See the buffer documentation for information on reading into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Read some data from the serial port.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);

This function is used to read data from the serial port. The function call will block until one or more bytes of data has been read successfully, or until an error occurs.

Parameters

buffers

One or more buffers into which the data will be read.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes read. Returns 0 if an error occurred.

Remarks

The read_some operation may not read all of the requested number of bytes. Consider using the read function if you need to ensure that the requested amount of data is read before the blocking operation completes.

Send a break sequence to the serial port.

void send_break();
  » more...

boost::system::error_code send_break(
    boost::system::error_code & ec);
  » more...

Send a break sequence to the serial port.

void send_break();

This function causes a break sequence of platform-specific duration to be sent out the serial port.

Exceptions

boost::system::system_error

Thrown on failure.

Send a break sequence to the serial port.

boost::system::error_code send_break(
    boost::system::error_code & ec);

This function causes a break sequence of platform-specific duration to be sent out the serial port.

Parameters

ec

Set to indicate what error occurred, if any.

Inherited from basic_io_object.

(Deprecated: Use get_service().) The service associated with the I/O object.

service_type & service;
Remarks

Available only for services that do not support movability.

Inherited from basic_io_object.

The type of the service that will be used to provide I/O operations.

typedef SerialPortService service_type;
Requirements

Header: boost/asio/basic_serial_port.hpp

Convenience header: boost/asio.hpp

Set an option on the serial port.

template<
    typename SettableSerialPortOption>
void set_option(
    const SettableSerialPortOption & option);
  » more...

template<
    typename SettableSerialPortOption>
boost::system::error_code set_option(
    const SettableSerialPortOption & option,
    boost::system::error_code & ec);
  » more...

Set an option on the serial port.

template<
    typename SettableSerialPortOption>
void set_option(
    const SettableSerialPortOption & option);

This function is used to set an option on the serial port.

Parameters

option

The option value to be set on the serial port.

Exceptions

boost::system::system_error

Thrown on failure.

Set an option on the serial port.

template<
    typename SettableSerialPortOption>
boost::system::error_code set_option(
    const SettableSerialPortOption & option,
    boost::system::error_code & ec);

This function is used to set an option on the serial port.

Parameters

option

The option value to be set on the serial port.

ec

Set to indicate what error occurred, if any.

Write some data to the serial port.

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers);
  » more...

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers,
    boost::system::error_code & ec);
  » more...

Write some data to the serial port.

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers);

This function is used to write data to the serial port. The function call will block until one or more bytes of the data has been written successfully, or until an error occurs.

Parameters

buffers

One or more data buffers to be written to the serial port.

Return Value

The number of bytes written.

Exceptions

boost::system::system_error

Thrown on failure. An error code of boost::asio::error::eof indicates that the connection was closed by the peer.

Remarks

The write_some operation may not transmit all of the data to the peer. Consider using the write function if you need to ensure that all data is written before the blocking operation completes.

Example

To write a single data buffer use the buffer function as follows:

serial_port.write_some(boost::asio::buffer(data, size));

See the buffer documentation for information on writing multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Write some data to the serial port.

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers,
    boost::system::error_code & ec);

This function is used to write data to the serial port. The function call will block until one or more bytes of the data has been written successfully, or until an error occurs.

Parameters

buffers

One or more data buffers to be written to the serial port.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes written. Returns 0 if an error occurred.

Remarks

The write_some operation may not transmit all of the data to the peer. Consider using the write function if you need to ensure that all data is written before the blocking operation completes.

Provides signal functionality.

template<
    typename SignalSetService = signal_set_service>
class basic_signal_set :
  public basic_io_object< SignalSetService >
Types

Name

Description

implementation_type

The underlying implementation type of I/O object.

service_type

The type of the service that will be used to provide I/O operations.

Member Functions

Name

Description

add

Add a signal to a signal_set.

async_wait

Start an asynchronous operation to wait for a signal to be delivered.

basic_signal_set

Construct a signal set without adding any signals.

Construct a signal set and add one signal.

Construct a signal set and add two signals.

Construct a signal set and add three signals.

cancel

Cancel all operations associated with the signal set.

clear

Remove all signals from a signal_set.

get_io_service

Get the io_service associated with the object.

remove

Remove a signal from a signal_set.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_signal_set class template provides the ability to perform an asynchronous wait for one or more signals to occur.

Most applications will use the signal_set typedef.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Example

Performing an asynchronous wait:

void handler(
    const boost::system::error_code& error,
    int signal_number)
{
  if (!error)
  {
    // A signal occurred.
  }
}

...

// Construct a signal set registered for process termination.
boost::asio::signal_set signals(io_service, SIGINT, SIGTERM);

// Start an asynchronous wait for one of the signals to occur.
signals.async_wait(handler);
Queueing of signal notifications

If a signal is registered with a signal_set, and the signal occurs when there are no waiting handlers, then the signal notification is queued. The next async_wait operation on that signal_set will dequeue the notification. If multiple notifications are queued, subsequent async_wait operations dequeue them one at a time. Signal notifications are dequeued in order of ascending signal number.

If a signal number is removed from a signal_set (using the remove or erase member functions) then any queued notifications for that signal are discarded.

Multiple registration of signals

The same signal number may be registered with different signal_set objects. When the signal occurs, one handler is called for each signal_set object.

Note that multiple registration only works for signals that are registered using Asio. The application must not also register a signal handler using functions such as signal() or sigaction().

Signal masking on POSIX platforms

POSIX allows signals to be blocked using functions such as sigprocmask() and pthread_sigmask(). For signals to be delivered, programs must ensure that any signals registered using signal_set objects are unblocked in at least one thread.

Requirements

Header: boost/asio/basic_signal_set.hpp

Convenience header: boost/asio.hpp

Add a signal to a signal_set.

void add(
    int signal_number);
  » more...

boost::system::error_code add(
    int signal_number,
    boost::system::error_code & ec);
  » more...

Add a signal to a signal_set.

void add(
    int signal_number);

This function adds the specified signal to the set. It has no effect if the signal is already in the set.

Parameters

signal_number

The signal to be added to the set.

Exceptions

boost::system::system_error

Thrown on failure.

Add a signal to a signal_set.

boost::system::error_code add(
    int signal_number,
    boost::system::error_code & ec);

This function adds the specified signal to the set. It has no effect if the signal is already in the set.

Parameters

signal_number

The signal to be added to the set.

ec

Set to indicate what error occurred, if any.

Start an asynchronous operation to wait for a signal to be delivered.

template<
    typename SignalHandler>
void-or-deduced async_wait(
    SignalHandler handler);

This function may be used to initiate an asynchronous wait against the signal set. It always returns immediately.

For each call to async_wait(), the supplied handler will be called exactly once. The handler will be called when:

  • One of the registered signals in the signal set occurs; or
  • The signal set was cancelled, in which case the handler is passed the error code boost::asio::error::operation_aborted.
Parameters

handler

The handler to be called when the signal occurs. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  int signal_number // Indicates which signal occurred.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Construct a signal set without adding any signals.

explicit basic_signal_set(
    boost::asio::io_service & io_service);
  » more...

Construct a signal set and add one signal.

basic_signal_set(
    boost::asio::io_service & io_service,
    int signal_number_1);
  » more...

Construct a signal set and add two signals.

basic_signal_set(
    boost::asio::io_service & io_service,
    int signal_number_1,
    int signal_number_2);
  » more...

Construct a signal set and add three signals.

basic_signal_set(
    boost::asio::io_service & io_service,
    int signal_number_1,
    int signal_number_2,
    int signal_number_3);
  » more...

Construct a signal set without adding any signals.

basic_signal_set(
    boost::asio::io_service & io_service);

This constructor creates a signal set without registering for any signals.

Parameters

io_service

The io_service object that the signal set will use to dispatch handlers for any asynchronous operations performed on the set.

Construct a signal set and add one signal.

basic_signal_set(
    boost::asio::io_service & io_service,
    int signal_number_1);

This constructor creates a signal set and registers for one signal.

Parameters

io_service

The io_service object that the signal set will use to dispatch handlers for any asynchronous operations performed on the set.

signal_number_1

The signal number to be added.

Remarks

This constructor is equivalent to performing:

boost::asio::signal_set signals(io_service);
signals.add(signal_number_1);

Construct a signal set and add two signals.

basic_signal_set(
    boost::asio::io_service & io_service,
    int signal_number_1,
    int signal_number_2);

This constructor creates a signal set and registers for two signals.

Parameters

io_service

The io_service object that the signal set will use to dispatch handlers for any asynchronous operations performed on the set.

signal_number_1

The first signal number to be added.

signal_number_2

The second signal number to be added.

Remarks

This constructor is equivalent to performing:

boost::asio::signal_set signals(io_service);
signals.add(signal_number_1);
signals.add(signal_number_2);

Construct a signal set and add three signals.

basic_signal_set(
    boost::asio::io_service & io_service,
    int signal_number_1,
    int signal_number_2,
    int signal_number_3);

This constructor creates a signal set and registers for three signals.

Parameters

io_service

The io_service object that the signal set will use to dispatch handlers for any asynchronous operations performed on the set.

signal_number_1

The first signal number to be added.

signal_number_2

The second signal number to be added.

signal_number_3

The third signal number to be added.

Remarks

This constructor is equivalent to performing:

boost::asio::signal_set signals(io_service);
signals.add(signal_number_1);
signals.add(signal_number_2);
signals.add(signal_number_3);

Cancel all operations associated with the signal set.

void cancel();
  » more...

boost::system::error_code cancel(
    boost::system::error_code & ec);
  » more...

Cancel all operations associated with the signal set.

void cancel();

This function forces the completion of any pending asynchronous wait operations against the signal set. The handler for each cancelled operation will be invoked with the boost::asio::error::operation_aborted error code.

Cancellation does not alter the set of registered signals.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

If a registered signal occurred before cancel() is called, then the handlers for asynchronous wait operations will:

  • have already been invoked; or
  • have been queued for invocation in the near future.

These handlers can no longer be cancelled, and therefore are passed an error code that indicates the successful completion of the wait operation.

Cancel all operations associated with the signal set.

boost::system::error_code cancel(
    boost::system::error_code & ec);

This function forces the completion of any pending asynchronous wait operations against the signal set. The handler for each cancelled operation will be invoked with the boost::asio::error::operation_aborted error code.

Cancellation does not alter the set of registered signals.

Parameters

ec

Set to indicate what error occurred, if any.

Remarks

If a registered signal occurred before cancel() is called, then the handlers for asynchronous wait operations will:

  • have already been invoked; or
  • have been queued for invocation in the near future.

These handlers can no longer be cancelled, and therefore are passed an error code that indicates the successful completion of the wait operation.

Remove all signals from a signal_set.

void clear();
  » more...

boost::system::error_code clear(
    boost::system::error_code & ec);
  » more...

Remove all signals from a signal_set.

void clear();

This function removes all signals from the set. It has no effect if the set is already empty.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Removes all queued notifications.

Remove all signals from a signal_set.

boost::system::error_code clear(
    boost::system::error_code & ec);

This function removes all signals from the set. It has no effect if the set is already empty.

Parameters

ec

Set to indicate what error occurred, if any.

Remarks

Removes all queued notifications.

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();
  » more...

const implementation_type & get_implementation() const;
  » more...

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

const implementation_type & get_implementation() const;

Inherited from basic_io_object.

Get the io_service associated with the object.

boost::asio::io_service & get_io_service();

This function may be used to obtain the io_service object that the I/O object uses to dispatch handlers for asynchronous operations.

Return Value

A reference to the io_service object that the I/O object will use to dispatch handlers. Ownership is not transferred to the caller.

Get the service associated with the I/O object.

service_type & get_service();
  » more...

const service_type & get_service() const;
  » more...

Inherited from basic_io_object.

Get the service associated with the I/O object.

service_type & get_service();

Inherited from basic_io_object.

Get the service associated with the I/O object.

const service_type & get_service() const;

Inherited from basic_io_object.

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

implementation_type implementation;

Inherited from basic_io_object.

The underlying implementation type of I/O object.

typedef service_type::implementation_type implementation_type;
Requirements

Header: boost/asio/basic_signal_set.hpp

Convenience header: boost/asio.hpp

Remove a signal from a signal_set.

void remove(
    int signal_number);
  » more...

boost::system::error_code remove(
    int signal_number,
    boost::system::error_code & ec);
  » more...

Remove a signal from a signal_set.

void remove(
    int signal_number);

This function removes the specified signal from the set. It has no effect if the signal is not in the set.

Parameters

signal_number

The signal to be removed from the set.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Removes any notifications that have been queued for the specified signal number.

Remove a signal from a signal_set.

boost::system::error_code remove(
    int signal_number,
    boost::system::error_code & ec);

This function removes the specified signal from the set. It has no effect if the signal is not in the set.

Parameters

signal_number

The signal to be removed from the set.

ec

Set to indicate what error occurred, if any.

Remarks

Removes any notifications that have been queued for the specified signal number.

Inherited from basic_io_object.

(Deprecated: Use get_service().) The service associated with the I/O object.

service_type & service;
Remarks

Available only for services that do not support movability.

Inherited from basic_io_object.

The type of the service that will be used to provide I/O operations.

typedef SignalSetService service_type;
Requirements

Header: boost/asio/basic_signal_set.hpp

Convenience header: boost/asio.hpp

basic_socket::assign
basic_socket::async_connect
basic_socket::at_mark
basic_socket::available
basic_socket::basic_socket
basic_socket::bind
basic_socket::broadcast
basic_socket::bytes_readable
basic_socket::cancel
basic_socket::close
basic_socket::connect
basic_socket::debug
basic_socket::do_not_route
basic_socket::enable_connection_aborted
basic_socket::endpoint_type
basic_socket::get_implementation
basic_socket::get_io_service
basic_socket::get_option
basic_socket::get_service
basic_socket::implementation
basic_socket::implementation_type
basic_socket::io_control
basic_socket::is_open
basic_socket::keep_alive
basic_socket::linger
basic_socket::local_endpoint
basic_socket::lowest_layer
basic_socket::lowest_layer_type
basic_socket::max_connections
basic_socket::message_do_not_route
basic_socket::message_end_of_record
basic_socket::message_flags
basic_socket::message_out_of_band
basic_socket::message_peek
basic_socket::native
basic_socket::native_handle
basic_socket::native_handle_type
basic_socket::native_non_blocking
basic_socket::native_type
basic_socket::non_blocking
basic_socket::non_blocking_io
basic_socket::open
basic_socket::operator=
basic_socket::protocol_type
basic_socket::receive_buffer_size
basic_socket::receive_low_watermark
basic_socket::remote_endpoint
basic_socket::reuse_address
basic_socket::send_buffer_size
basic_socket::send_low_watermark
basic_socket::service
basic_socket::service_type
basic_socket::set_option
basic_socket::shutdown
basic_socket::shutdown_type
basic_socket::~basic_socket

Provides socket functionality.

template<
    typename Protocol,
    typename SocketService>
class basic_socket :
  public basic_io_object< SocketService >,
  public socket_base
Types

Name

Description

broadcast

Socket option to permit sending of broadcast messages.

bytes_readable

IO control command to get the amount of data that can be read without blocking.

debug

Socket option to enable socket-level debugging.

do_not_route

Socket option to prevent routing, use local interfaces only.

enable_connection_aborted

Socket option to report aborted connections on accept.

endpoint_type

The endpoint type.

implementation_type

The underlying implementation type of I/O object.

keep_alive

Socket option to send keep-alives.

linger

Socket option to specify whether the socket lingers on close if unsent data is present.

lowest_layer_type

A basic_socket is always the lowest layer.

message_flags

Bitmask type for flags that can be passed to send and receive operations.

native_handle_type

The native representation of a socket.

native_type

(Deprecated: Use native_handle_type.) The native representation of a socket.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

protocol_type

The protocol type.

receive_buffer_size

Socket option for the receive buffer size of a socket.

receive_low_watermark

Socket option for the receive low watermark.

reuse_address

Socket option to allow the socket to be bound to an address that is already in use.

send_buffer_size

Socket option for the send buffer size of a socket.

send_low_watermark

Socket option for the send low watermark.

service_type

The type of the service that will be used to provide I/O operations.

shutdown_type

Different ways a socket may be shutdown.

Member Functions

Name

Description

assign

Assign an existing native socket to the socket.

async_connect

Start an asynchronous connect.

at_mark

Determine whether the socket is at the out-of-band data mark.

available

Determine the number of bytes available for reading.

basic_socket

Construct a basic_socket without opening it.

Construct and open a basic_socket.

Construct a basic_socket, opening it and binding it to the given local endpoint.

Construct a basic_socket on an existing native socket.

Move-construct a basic_socket from another.

Move-construct a basic_socket from a socket of another protocol type.

bind

Bind the socket to the given local endpoint.

cancel

Cancel all asynchronous operations associated with the socket.

close

Close the socket.

connect

Connect the socket to the specified endpoint.

get_io_service

Get the io_service associated with the object.

get_option

Get an option from the socket.

io_control

Perform an IO control command on the socket.

is_open

Determine whether the socket is open.

local_endpoint

Get the local endpoint of the socket.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native socket representation.

native_handle

Get the native socket representation.

native_non_blocking

Gets the non-blocking mode of the native socket implementation.

Sets the non-blocking mode of the native socket implementation.

non_blocking

Gets the non-blocking mode of the socket.

Sets the non-blocking mode of the socket.

open

Open the socket using the specified protocol.

operator=

Move-assign a basic_socket from another.

Move-assign a basic_socket from a socket of another protocol type.

remote_endpoint

Get the remote endpoint of the socket.

set_option

Set an option on the socket.

shutdown

Disable sends or receives on the socket.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

~basic_socket

Protected destructor to prevent deletion through this type.

Data Members

Name

Description

max_connections

The maximum length of the queue of pending incoming connections.

message_do_not_route

Specify that the data should not be subject to routing.

message_end_of_record

Specifies that the data marks the end of a record.

message_out_of_band

Process out-of-band data.

message_peek

Peek at incoming data without removing it from the input queue.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_socket class template provides functionality that is common to both stream-oriented and datagram-oriented sockets.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/basic_socket.hpp

Convenience header: boost/asio.hpp

Assign an existing native socket to the socket.

void assign(
    const protocol_type & protocol,
    const native_handle_type & native_socket);
  » more...

boost::system::error_code assign(
    const protocol_type & protocol,
    const native_handle_type & native_socket,
    boost::system::error_code & ec);
  » more...

Assign an existing native socket to the socket.

void assign(
    const protocol_type & protocol,
    const native_handle_type & native_socket);

Assign an existing native socket to the socket.

boost::system::error_code assign(
    const protocol_type & protocol,
    const native_handle_type & native_socket,
    boost::system::error_code & ec);

Start an asynchronous connect.

template<
    typename ConnectHandler>
void-or-deduced async_connect(
    const endpoint_type & peer_endpoint,
    ConnectHandler handler);

This function is used to asynchronously connect a socket to the specified remote endpoint. The function call always returns immediately.

The socket is automatically opened if it is not already open. If the connect fails, and the socket was automatically opened, the socket is not returned to the closed state.

Parameters

peer_endpoint

The remote endpoint to which the socket will be connected. Copies will be made of the endpoint object as required.

handler

The handler to be called when the connection operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error // Result of operation
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Example
void connect_handler(const boost::system::error_code& error)
{
  if (!error)
  {
    // Connect succeeded.
  }
}

...

boost::asio::ip::tcp::socket socket(io_service);
boost::asio::ip::tcp::endpoint endpoint(
    boost::asio::ip::address::from_string("1.2.3.4"), 12345);
socket.async_connect(endpoint, connect_handler);

Determine whether the socket is at the out-of-band data mark.

bool at_mark() const;
  » more...

bool at_mark(
    boost::system::error_code & ec) const;
  » more...

Determine whether the socket is at the out-of-band data mark.

bool at_mark() const;

This function is used to check whether the socket input is currently positioned at the out-of-band data mark.

Return Value

A bool indicating whether the socket is at the out-of-band data mark.

Exceptions

boost::system::system_error

Thrown on failure.

Determine whether the socket is at the out-of-band data mark.

bool at_mark(
    boost::system::error_code & ec) const;

This function is used to check whether the socket input is currently positioned at the out-of-band data mark.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

A bool indicating whether the socket is at the out-of-band data mark.

Determine the number of bytes available for reading.

std::size_t available() const;
  » more...

std::size_t available(
    boost::system::error_code & ec) const;
  » more...

Determine the number of bytes available for reading.

std::size_t available() const;

This function is used to determine the number of bytes that may be read without blocking.

Return Value

The number of bytes that may be read without blocking, or 0 if an error occurs.

Exceptions

boost::system::system_error

Thrown on failure.

Determine the number of bytes available for reading.

std::size_t available(
    boost::system::error_code & ec) const;

This function is used to determine the number of bytes that may be read without blocking.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes that may be read without blocking, or 0 if an error occurs.

Construct a basic_socket without opening it.

explicit basic_socket(
    boost::asio::io_service & io_service);
  » more...

Construct and open a basic_socket.

basic_socket(
    boost::asio::io_service & io_service,
    const protocol_type & protocol);
  » more...

Construct a basic_socket, opening it and binding it to the given local endpoint.

basic_socket(
    boost::asio::io_service & io_service,
    const endpoint_type & endpoint);
  » more...

Construct a basic_socket on an existing native socket.

basic_socket(
    boost::asio::io_service & io_service,
    const protocol_type & protocol,
    const native_handle_type & native_socket);
  » more...

Move-construct a basic_socket from another.

basic_socket(
    basic_socket && other);
  » more...

Move-construct a basic_socket from a socket of another protocol type.

template<
    typename Protocol1,
    typename SocketService1>
basic_socket(
    basic_socket< Protocol1, SocketService1 > && other,
    typename enable_if< is_convertible< Protocol1, Protocol >::value >::type *  = 0);
  » more...

Construct a basic_socket without opening it.

basic_socket(
    boost::asio::io_service & io_service);

This constructor creates a socket without opening it.

Parameters

io_service

The io_service object that the socket will use to dispatch handlers for any asynchronous operations performed on the socket.

Construct and open a basic_socket.

basic_socket(
    boost::asio::io_service & io_service,
    const protocol_type & protocol);

This constructor creates and opens a socket.

Parameters

io_service

The io_service object that the socket will use to dispatch handlers for any asynchronous operations performed on the socket.

protocol

An object specifying protocol parameters to be used.

Exceptions

boost::system::system_error

Thrown on failure.

Construct a basic_socket, opening it and binding it to the given local endpoint.

basic_socket(
    boost::asio::io_service & io_service,
    const endpoint_type & endpoint);

This constructor creates a socket and automatically opens it bound to the specified endpoint on the local machine. The protocol used is the protocol associated with the given endpoint.

Parameters

io_service

The io_service object that the socket will use to dispatch handlers for any asynchronous operations performed on the socket.

endpoint

An endpoint on the local machine to which the socket will be bound.

Exceptions

boost::system::system_error

Thrown on failure.

Construct a basic_socket on an existing native socket.

basic_socket(
    boost::asio::io_service & io_service,
    const protocol_type & protocol,
    const native_handle_type & native_socket);

This constructor creates a socket object to hold an existing native socket.

Parameters

io_service

The io_service object that the socket will use to dispatch handlers for any asynchronous operations performed on the socket.

protocol

An object specifying protocol parameters to be used.

native_socket

A native socket.

Exceptions

boost::system::system_error

Thrown on failure.

Move-construct a basic_socket from another.

basic_socket(
    basic_socket && other);

This constructor moves a socket from one object to another.

Parameters

other

The other basic_socket object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_socket(io_service&) constructor.

Move-construct a basic_socket from a socket of another protocol type.

template<
    typename Protocol1,
    typename SocketService1>
basic_socket(
    basic_socket< Protocol1, SocketService1 > && other,
    typename enable_if< is_convertible< Protocol1, Protocol >::value >::type *  = 0);

This constructor moves a socket from one object to another.

Parameters

other

The other basic_socket object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_socket(io_service&) constructor.

Bind the socket to the given local endpoint.

void bind(
    const endpoint_type & endpoint);
  » more...

boost::system::error_code bind(
    const endpoint_type & endpoint,
    boost::system::error_code & ec);
  » more...

Bind the socket to the given local endpoint.

void bind(
    const endpoint_type & endpoint);

This function binds the socket to the specified endpoint on the local machine.

Parameters

endpoint

An endpoint on the local machine to which the socket will be bound.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::socket socket(io_service);
socket.open(boost::asio::ip::tcp::v4());
socket.bind(boost::asio::ip::tcp::endpoint(
      boost::asio::ip::tcp::v4(), 12345));

Bind the socket to the given local endpoint.

boost::system::error_code bind(
    const endpoint_type & endpoint,
    boost::system::error_code & ec);

This function binds the socket to the specified endpoint on the local machine.

Parameters

endpoint

An endpoint on the local machine to which the socket will be bound.

ec

Set to indicate what error occurred, if any.

Example
boost::asio::ip::tcp::socket socket(io_service);
socket.open(boost::asio::ip::tcp::v4());
boost::system::error_code ec;
socket.bind(boost::asio::ip::tcp::endpoint(
      boost::asio::ip::tcp::v4(), 12345), ec);
if (ec)
{
  // An error occurred.
}

Inherited from socket_base.

Socket option to permit sending of broadcast messages.

typedef implementation_defined broadcast;

Implements the SOL_SOCKET/SO_BROADCAST socket option.

Examples

Setting the option:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::broadcast option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::broadcast option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

IO control command to get the amount of data that can be read without blocking.

typedef implementation_defined bytes_readable;

Implements the FIONREAD IO control command.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::bytes_readable command(true);
socket.io_control(command);
std::size_t bytes_readable = command.get();
Requirements

Header: boost/asio/basic_socket.hpp

Convenience header: boost/asio.hpp

Cancel all asynchronous operations associated with the socket.

void cancel();
  » more...

boost::system::error_code cancel(
    boost::system::error_code & ec);
  » more...

Cancel all asynchronous operations associated with the socket.

void cancel();

This function causes all outstanding asynchronous connect, send and receive operations to finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Calls to cancel() will always fail with boost::asio::error::operation_not_supported when run on Windows XP, Windows Server 2003, and earlier versions of Windows, unless BOOST_ASIO_ENABLE_CANCELIO is defined. However, the CancelIo function has two issues that should be considered before enabling its use:

  • It will only cancel asynchronous operations that were initiated in the current thread.
  • It can appear to complete without error, but the request to cancel the unfinished operations may be silently ignored by the operating system. Whether it works or not seems to depend on the drivers that are installed.

For portable cancellation, consider using one of the following alternatives:

  • Disable asio's I/O completion port backend by defining BOOST_ASIO_DISABLE_IOCP.
  • Use the close() function to simultaneously cancel the outstanding operations and close the socket.

When running on Windows Vista, Windows Server 2008, and later, the CancelIoEx function is always used. This function does not have the problems described above.

Cancel all asynchronous operations associated with the socket.

boost::system::error_code cancel(
    boost::system::error_code & ec);

This function causes all outstanding asynchronous connect, send and receive operations to finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error.

Parameters

ec

Set to indicate what error occurred, if any.

Remarks

Calls to cancel() will always fail with boost::asio::error::operation_not_supported when run on Windows XP, Windows Server 2003, and earlier versions of Windows, unless BOOST_ASIO_ENABLE_CANCELIO is defined. However, the CancelIo function has two issues that should be considered before enabling its use:

  • It will only cancel asynchronous operations that were initiated in the current thread.
  • It can appear to complete without error, but the request to cancel the unfinished operations may be silently ignored by the operating system. Whether it works or not seems to depend on the drivers that are installed.

For portable cancellation, consider using one of the following alternatives:

  • Disable asio's I/O completion port backend by defining BOOST_ASIO_DISABLE_IOCP.
  • Use the close() function to simultaneously cancel the outstanding operations and close the socket.

When running on Windows Vista, Windows Server 2008, and later, the CancelIoEx function is always used. This function does not have the problems described above.

Close the socket.

void close();
  » more...

boost::system::error_code close(
    boost::system::error_code & ec);
  » more...

Close the socket.

void close();

This function is used to close the socket. Any asynchronous send, receive or connect operations will be cancelled immediately, and will complete with the boost::asio::error::operation_aborted error.

Exceptions

boost::system::system_error

Thrown on failure. Note that, even if the function indicates an error, the underlying descriptor is closed.

Remarks

For portable behaviour with respect to graceful closure of a connected socket, call shutdown() before closing the socket.

Close the socket.

boost::system::error_code close(
    boost::system::error_code & ec);

This function is used to close the socket. Any asynchronous send, receive or connect operations will be cancelled immediately, and will complete with the boost::asio::error::operation_aborted error.

Parameters

ec

Set to indicate what error occurred, if any. Note that, even if the function indicates an error, the underlying descriptor is closed.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::system::error_code ec;
socket.close(ec);
if (ec)
{
  // An error occurred.
}
Remarks

For portable behaviour with respect to graceful closure of a connected socket, call shutdown() before closing the socket.

Connect the socket to the specified endpoint.

void connect(
    const endpoint_type & peer_endpoint);
  » more...

boost::system::error_code connect(
    const endpoint_type & peer_endpoint,
    boost::system::error_code & ec);
  » more...

Connect the socket to the specified endpoint.

void connect(
    const endpoint_type & peer_endpoint);

This function is used to connect a socket to the specified remote endpoint. The function call will block until the connection is successfully made or an error occurs.

The socket is automatically opened if it is not already open. If the connect fails, and the socket was automatically opened, the socket is not returned to the closed state.

Parameters

peer_endpoint

The remote endpoint to which the socket will be connected.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::socket socket(io_service);
boost::asio::ip::tcp::endpoint endpoint(
    boost::asio::ip::address::from_string("1.2.3.4"), 12345);
socket.connect(endpoint);

Connect the socket to the specified endpoint.

boost::system::error_code connect(
    const endpoint_type & peer_endpoint,
    boost::system::error_code & ec);

This function is used to connect a socket to the specified remote endpoint. The function call will block until the connection is successfully made or an error occurs.

The socket is automatically opened if it is not already open. If the connect fails, and the socket was automatically opened, the socket is not returned to the closed state.

Parameters

peer_endpoint

The remote endpoint to which the socket will be connected.

ec

Set to indicate what error occurred, if any.

Example
boost::asio::ip::tcp::socket socket(io_service);
boost::asio::ip::tcp::endpoint endpoint(
    boost::asio::ip::address::from_string("1.2.3.4"), 12345);
boost::system::error_code ec;
socket.connect(endpoint, ec);
if (ec)
{
  // An error occurred.
}

Inherited from socket_base.

Socket option to enable socket-level debugging.

typedef implementation_defined debug;

Implements the SOL_SOCKET/SO_DEBUG socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::debug option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::debug option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option to prevent routing, use local interfaces only.

typedef implementation_defined do_not_route;

Implements the SOL_SOCKET/SO_DONTROUTE socket option.

Examples

Setting the option:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::do_not_route option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::do_not_route option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option to report aborted connections on accept.

typedef implementation_defined enable_connection_aborted;

Implements a custom socket option that determines whether or not an accept operation is permitted to fail with boost::asio::error::connection_aborted. By default the option is false.

Examples

Setting the option:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::enable_connection_aborted option(true);
acceptor.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::enable_connection_aborted option;
acceptor.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_socket.hpp

Convenience header: boost/asio.hpp

The endpoint type.

typedef Protocol::endpoint endpoint_type;
Requirements

Header: boost/asio/basic_socket.hpp

Convenience header: boost/asio.hpp

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();
  » more...

const implementation_type & get_implementation() const;
  » more...

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

const implementation_type & get_implementation() const;

Inherited from basic_io_object.

Get the io_service associated with the object.

boost::asio::io_service & get_io_service();

This function may be used to obtain the io_service object that the I/O object uses to dispatch handlers for asynchronous operations.

Return Value

A reference to the io_service object that the I/O object will use to dispatch handlers. Ownership is not transferred to the caller.

Get an option from the socket.

template<
    typename GettableSocketOption>
void get_option(
    GettableSocketOption & option) const;
  » more...

template<
    typename GettableSocketOption>
boost::system::error_code get_option(
    GettableSocketOption & option,
    boost::system::error_code & ec) const;
  » more...

Get an option from the socket.

template<
    typename GettableSocketOption>
void get_option(
    GettableSocketOption & option) const;

This function is used to get the current value of an option on the socket.

Parameters

option

The option value to be obtained from the socket.

Exceptions

boost::system::system_error

Thrown on failure.

Example

Getting the value of the SOL_SOCKET/SO_KEEPALIVE option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::socket::keep_alive option;
socket.get_option(option);
bool is_set = option.value();

Get an option from the socket.

template<
    typename GettableSocketOption>
boost::system::error_code get_option(
    GettableSocketOption & option,
    boost::system::error_code & ec) const;

This function is used to get the current value of an option on the socket.

Parameters

option

The option value to be obtained from the socket.

ec

Set to indicate what error occurred, if any.

Example

Getting the value of the SOL_SOCKET/SO_KEEPALIVE option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::socket::keep_alive option;
boost::system::error_code ec;
socket.get_option(option, ec);
if (ec)
{
  // An error occurred.
}
bool is_set = option.value();

Get the service associated with the I/O object.

service_type & get_service();
  » more...

const service_type & get_service() const;
  » more...

Inherited from basic_io_object.

Get the service associated with the I/O object.

service_type & get_service();

Inherited from basic_io_object.

Get the service associated with the I/O object.

const service_type & get_service() const;

Inherited from basic_io_object.

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

implementation_type implementation;

Inherited from basic_io_object.

The underlying implementation type of I/O object.

typedef service_type::implementation_type implementation_type;
Requirements

Header: boost/asio/basic_socket.hpp

Convenience header: boost/asio.hpp

Perform an IO control command on the socket.

template<
    typename IoControlCommand>
void io_control(
    IoControlCommand & command);
  » more...

template<
    typename IoControlCommand>
boost::system::error_code io_control(
    IoControlCommand & command,
    boost::system::error_code & ec);
  » more...

Perform an IO control command on the socket.

template<
    typename IoControlCommand>
void io_control(
    IoControlCommand & command);

This function is used to execute an IO control command on the socket.

Parameters

command

The IO control command to be performed on the socket.

Exceptions

boost::system::system_error

Thrown on failure.

Example

Getting the number of bytes ready to read:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::socket::bytes_readable command;
socket.io_control(command);
std::size_t bytes_readable = command.get();

Perform an IO control command on the socket.

template<
    typename IoControlCommand>
boost::system::error_code io_control(
    IoControlCommand & command,
    boost::system::error_code & ec);

This function is used to execute an IO control command on the socket.

Parameters

command

The IO control command to be performed on the socket.

ec

Set to indicate what error occurred, if any.

Example

Getting the number of bytes ready to read:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::socket::bytes_readable command;
boost::system::error_code ec;
socket.io_control(command, ec);
if (ec)
{
  // An error occurred.
}
std::size_t bytes_readable = command.get();

Determine whether the socket is open.

bool is_open() const;

Inherited from socket_base.

Socket option to send keep-alives.

typedef implementation_defined keep_alive;

Implements the SOL_SOCKET/SO_KEEPALIVE socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::keep_alive option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::keep_alive option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

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.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::linger option(true, 30);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::linger option;
socket.get_option(option);
bool is_set = option.enabled();
unsigned short timeout = option.timeout();
Requirements

Header: boost/asio/basic_socket.hpp

Convenience header: boost/asio.hpp

Get the local endpoint of the socket.

endpoint_type local_endpoint() const;
  » more...

endpoint_type local_endpoint(
    boost::system::error_code & ec) const;
  » more...

Get the local endpoint of the socket.

endpoint_type local_endpoint() const;

This function is used to obtain the locally bound endpoint of the socket.

Return Value

An object that represents the local endpoint of the socket.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::endpoint endpoint = socket.local_endpoint();

Get the local endpoint of the socket.

endpoint_type local_endpoint(
    boost::system::error_code & ec) const;

This function is used to obtain the locally bound endpoint of the socket.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

An object that represents the local endpoint of the socket. Returns a default-constructed endpoint object if an error occurred.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::system::error_code ec;
boost::asio::ip::tcp::endpoint endpoint = socket.local_endpoint(ec);
if (ec)
{
  // An error occurred.
}

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();
  » more...

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;
  » more...

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();

This function returns a reference to the lowest layer in a stack of layers. Since a basic_socket cannot contain any further layers, it simply returns a reference to itself.

Return Value

A reference to the lowest layer in the stack of layers. Ownership is not transferred to the caller.

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;

This function returns a const reference to the lowest layer in a stack of layers. Since a basic_socket cannot contain any further layers, it simply returns a reference to itself.

Return Value

A const reference to the lowest layer in the stack of layers. Ownership is not transferred to the caller.

A basic_socket is always the lowest layer.

typedef basic_socket< Protocol, SocketService > lowest_layer_type;
Types

Name

Description

broadcast

Socket option to permit sending of broadcast messages.

bytes_readable

IO control command to get the amount of data that can be read without blocking.

debug

Socket option to enable socket-level debugging.

do_not_route

Socket option to prevent routing, use local interfaces only.

enable_connection_aborted

Socket option to report aborted connections on accept.

endpoint_type

The endpoint type.

implementation_type

The underlying implementation type of I/O object.

keep_alive

Socket option to send keep-alives.

linger

Socket option to specify whether the socket lingers on close if unsent data is present.

lowest_layer_type

A basic_socket is always the lowest layer.

message_flags

Bitmask type for flags that can be passed to send and receive operations.

native_handle_type

The native representation of a socket.

native_type

(Deprecated: Use native_handle_type.) The native representation of a socket.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

protocol_type

The protocol type.

receive_buffer_size

Socket option for the receive buffer size of a socket.

receive_low_watermark

Socket option for the receive low watermark.

reuse_address

Socket option to allow the socket to be bound to an address that is already in use.

send_buffer_size

Socket option for the send buffer size of a socket.

send_low_watermark

Socket option for the send low watermark.

service_type

The type of the service that will be used to provide I/O operations.

shutdown_type

Different ways a socket may be shutdown.

Member Functions

Name

Description

assign

Assign an existing native socket to the socket.

async_connect

Start an asynchronous connect.

at_mark

Determine whether the socket is at the out-of-band data mark.

available

Determine the number of bytes available for reading.

basic_socket

Construct a basic_socket without opening it.

Construct and open a basic_socket.

Construct a basic_socket, opening it and binding it to the given local endpoint.

Construct a basic_socket on an existing native socket.

Move-construct a basic_socket from another.

Move-construct a basic_socket from a socket of another protocol type.

bind

Bind the socket to the given local endpoint.

cancel

Cancel all asynchronous operations associated with the socket.

close

Close the socket.

connect

Connect the socket to the specified endpoint.

get_io_service

Get the io_service associated with the object.

get_option

Get an option from the socket.

io_control

Perform an IO control command on the socket.

is_open

Determine whether the socket is open.

local_endpoint

Get the local endpoint of the socket.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native socket representation.

native_handle

Get the native socket representation.

native_non_blocking

Gets the non-blocking mode of the native socket implementation.

Sets the non-blocking mode of the native socket implementation.

non_blocking

Gets the non-blocking mode of the socket.

Sets the non-blocking mode of the socket.

open

Open the socket using the specified protocol.

operator=

Move-assign a basic_socket from another.

Move-assign a basic_socket from a socket of another protocol type.

remote_endpoint

Get the remote endpoint of the socket.

set_option

Set an option on the socket.

shutdown

Disable sends or receives on the socket.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

~basic_socket

Protected destructor to prevent deletion through this type.

Data Members

Name

Description

max_connections

The maximum length of the queue of pending incoming connections.

message_do_not_route

Specify that the data should not be subject to routing.

message_end_of_record

Specifies that the data marks the end of a record.

message_out_of_band

Process out-of-band data.

message_peek

Peek at incoming data without removing it from the input queue.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_socket class template provides functionality that is common to both stream-oriented and datagram-oriented sockets.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/basic_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

The maximum length of the queue of pending incoming connections.

static const int max_connections = implementation_defined;

Inherited from socket_base.

Specify that the data should not be subject to routing.

static const int message_do_not_route = implementation_defined;

Inherited from socket_base.

Specifies that the data marks the end of a record.

static const int message_end_of_record = implementation_defined;

Inherited from socket_base.

Bitmask type for flags that can be passed to send and receive operations.

typedef int message_flags;
Requirements

Header: boost/asio/basic_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Process out-of-band data.

static const int message_out_of_band = implementation_defined;

Inherited from socket_base.

Peek at incoming data without removing it from the input queue.

static const int message_peek = implementation_defined;

(Deprecated: Use native_handle().) Get the native socket representation.

native_type native();

This function may be used to obtain the underlying representation of the socket. This is intended to allow access to native socket functionality that is not otherwise provided.

Get the native socket representation.

native_handle_type native_handle();

This function may be used to obtain the underlying representation of the socket. This is intended to allow access to native socket functionality that is not otherwise provided.

The native representation of a socket.

typedef SocketService::native_handle_type native_handle_type;
Requirements

Header: boost/asio/basic_socket.hpp

Convenience header: boost/asio.hpp

Gets the non-blocking mode of the native socket implementation.

bool native_non_blocking() const;
  » more...

Sets the non-blocking mode of the native socket implementation.

void native_non_blocking(
    bool mode);
  » more...

boost::system::error_code native_non_blocking(
    bool mode,
    boost::system::error_code & ec);
  » more...

Gets the non-blocking mode of the native socket implementation.

bool native_non_blocking() const;

This function is used to retrieve the non-blocking mode of the underlying native socket. This mode has no effect on the behaviour of the socket object's synchronous operations.

Return Value

true if the underlying socket is in non-blocking mode and direct system calls may fail with boost::asio::error::would_block (or the equivalent system error).

Remarks

The current non-blocking mode is cached by the socket object. Consequently, the return value may be incorrect if the non-blocking mode was set directly on the native socket.

Example

This function is intended to allow the encapsulation of arbitrary non-blocking system calls as asynchronous operations, in a way that is transparent to the user of the socket object. The following example illustrates how Linux's sendfile system call might be encapsulated:

template <typename Handler>
struct sendfile_op
{
  tcp::socket& sock_;
  int fd_;
  Handler handler_;
  off_t offset_;
  std::size_t total_bytes_transferred_;

  // Function call operator meeting WriteHandler requirements.
  // Used as the handler for the async_write_some operation.
  void operator()(boost::system::error_code ec, std::size_t)
  {
    // Put the underlying socket into non-blocking mode.
    if (!ec)
      if (!sock_.native_non_blocking())
        sock_.native_non_blocking(true, ec);

    if (!ec)
    {
      for (;;)
      {
        // Try the system call.
        errno = 0;
        int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536);
        ec = boost::system::error_code(n < 0 ? errno : 0,
            boost::asio::error::get_system_category());
        total_bytes_transferred_ += ec ? 0 : n;

        // Retry operation immediately if interrupted by signal.
        if (ec == boost::asio::error::interrupted)
          continue;

        // Check if we need to run the operation again.
        if (ec == boost::asio::error::would_block
            || ec == boost::asio::error::try_again)
        {
          // We have to wait for the socket to become ready again.
          sock_.async_write_some(boost::asio::null_buffers(), *this);
          return;
        }

        if (ec || n == 0)
        {
          // An error occurred, or we have reached the end of the file.
          // Either way we must exit the loop so we can call the handler.
          break;
        }

        // Loop around to try calling sendfile again.
      }
    }

    // Pass result back to user's handler.
    handler_(ec, total_bytes_transferred_);
  }
};

template <typename Handler>
void async_sendfile(tcp::socket& sock, int fd, Handler h)
{
  sendfile_op<Handler> op = { sock, fd, h, 0, 0 };
  sock.async_write_some(boost::asio::null_buffers(), op);
}

Sets the non-blocking mode of the native socket implementation.

void native_non_blocking(
    bool mode);

This function is used to modify the non-blocking mode of the underlying native socket. It has no effect on the behaviour of the socket object's synchronous operations.

Parameters

mode

If true, the underlying socket is put into non-blocking mode and direct system calls may fail with boost::asio::error::would_block (or the equivalent system error).

Exceptions

boost::system::system_error

Thrown on failure. If the mode is false, but the current value of non_blocking() is true, this function fails with boost::asio::error::invalid_argument, as the combination does not make sense.

Example

This function is intended to allow the encapsulation of arbitrary non-blocking system calls as asynchronous operations, in a way that is transparent to the user of the socket object. The following example illustrates how Linux's sendfile system call might be encapsulated:

template <typename Handler>
struct sendfile_op
{
  tcp::socket& sock_;
  int fd_;
  Handler handler_;
  off_t offset_;
  std::size_t total_bytes_transferred_;

  // Function call operator meeting WriteHandler requirements.
  // Used as the handler for the async_write_some operation.
  void operator()(boost::system::error_code ec, std::size_t)
  {
    // Put the underlying socket into non-blocking mode.
    if (!ec)
      if (!sock_.native_non_blocking())
        sock_.native_non_blocking(true, ec);

    if (!ec)
    {
      for (;;)
      {
        // Try the system call.
        errno = 0;
        int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536);
        ec = boost::system::error_code(n < 0 ? errno : 0,
            boost::asio::error::get_system_category());
        total_bytes_transferred_ += ec ? 0 : n;

        // Retry operation immediately if interrupted by signal.
        if (ec == boost::asio::error::interrupted)
          continue;

        // Check if we need to run the operation again.
        if (ec == boost::asio::error::would_block
            || ec == boost::asio::error::try_again)
        {
          // We have to wait for the socket to become ready again.
          sock_.async_write_some(boost::asio::null_buffers(), *this);
          return;
        }

        if (ec || n == 0)
        {
          // An error occurred, or we have reached the end of the file.
          // Either way we must exit the loop so we can call the handler.
          break;
        }

        // Loop around to try calling sendfile again.
      }
    }

    // Pass result back to user's handler.
    handler_(ec, total_bytes_transferred_);
  }
};

template <typename Handler>
void async_sendfile(tcp::socket& sock, int fd, Handler h)
{
  sendfile_op<Handler> op = { sock, fd, h, 0, 0 };
  sock.async_write_some(boost::asio::null_buffers(), op);
}

Sets the non-blocking mode of the native socket implementation.

boost::system::error_code native_non_blocking(
    bool mode,
    boost::system::error_code & ec);

This function is used to modify the non-blocking mode of the underlying native socket. It has no effect on the behaviour of the socket object's synchronous operations.

Parameters

mode

If true, the underlying socket is put into non-blocking mode and direct system calls may fail with boost::asio::error::would_block (or the equivalent system error).

ec

Set to indicate what error occurred, if any. If the mode is false, but the current value of non_blocking() is true, this function fails with boost::asio::error::invalid_argument, as the combination does not make sense.

Example

This function is intended to allow the encapsulation of arbitrary non-blocking system calls as asynchronous operations, in a way that is transparent to the user of the socket object. The following example illustrates how Linux's sendfile system call might be encapsulated:

template <typename Handler>
struct sendfile_op
{
  tcp::socket& sock_;
  int fd_;
  Handler handler_;
  off_t offset_;
  std::size_t total_bytes_transferred_;

  // Function call operator meeting WriteHandler requirements.
  // Used as the handler for the async_write_some operation.
  void operator()(boost::system::error_code ec, std::size_t)
  {
    // Put the underlying socket into non-blocking mode.
    if (!ec)
      if (!sock_.native_non_blocking())
        sock_.native_non_blocking(true, ec);

    if (!ec)
    {
      for (;;)
      {
        // Try the system call.
        errno = 0;
        int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536);
        ec = boost::system::error_code(n < 0 ? errno : 0,
            boost::asio::error::get_system_category());
        total_bytes_transferred_ += ec ? 0 : n;

        // Retry operation immediately if interrupted by signal.
        if (ec == boost::asio::error::interrupted)
          continue;

        // Check if we need to run the operation again.
        if (ec == boost::asio::error::would_block
            || ec == boost::asio::error::try_again)
        {
          // We have to wait for the socket to become ready again.
          sock_.async_write_some(boost::asio::null_buffers(), *this);
          return;
        }

        if (ec || n == 0)
        {
          // An error occurred, or we have reached the end of the file.
          // Either way we must exit the loop so we can call the handler.
          break;
        }

        // Loop around to try calling sendfile again.
      }
    }

    // Pass result back to user's handler.
    handler_(ec, total_bytes_transferred_);
  }
};

template <typename Handler>
void async_sendfile(tcp::socket& sock, int fd, Handler h)
{
  sendfile_op<Handler> op = { sock, fd, h, 0, 0 };
  sock.async_write_some(boost::asio::null_buffers(), op);
}

(Deprecated: Use native_handle_type.) The native representation of a socket.

typedef SocketService::native_handle_type native_type;
Requirements

Header: boost/asio/basic_socket.hpp

Convenience header: boost/asio.hpp

Gets the non-blocking mode of the socket.

bool non_blocking() const;
  » more...

Sets the non-blocking mode of the socket.

void non_blocking(
    bool mode);
  » more...

boost::system::error_code non_blocking(
    bool mode,
    boost::system::error_code & ec);
  » more...

Gets the non-blocking mode of the socket.

bool non_blocking() const;
Return Value

true if the socket's synchronous operations will fail with boost::asio::error::would_block if they are unable to perform the requested operation immediately. If false, synchronous operations will block until complete.

Remarks

The non-blocking mode has no effect on the behaviour of asynchronous operations. Asynchronous operations will never fail with the error boost::asio::error::would_block.

Sets the non-blocking mode of the socket.

void non_blocking(
    bool mode);
Parameters

mode

If true, the socket's synchronous operations will fail with boost::asio::error::would_block if they are unable to perform the requested operation immediately. If false, synchronous operations will block until complete.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

The non-blocking mode has no effect on the behaviour of asynchronous operations. Asynchronous operations will never fail with the error boost::asio::error::would_block.

Sets the non-blocking mode of the socket.

boost::system::error_code non_blocking(
    bool mode,
    boost::system::error_code & ec);
Parameters

mode

If true, the socket's synchronous operations will fail with boost::asio::error::would_block if they are unable to perform the requested operation immediately. If false, synchronous operations will block until complete.

ec

Set to indicate what error occurred, if any.

Remarks

The non-blocking mode has no effect on the behaviour of asynchronous operations. Asynchronous operations will never fail with the error boost::asio::error::would_block.

Inherited from socket_base.

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

typedef implementation_defined non_blocking_io;

Implements the FIONBIO IO control command.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::non_blocking_io command(true);
socket.io_control(command);
Requirements

Header: boost/asio/basic_socket.hpp

Convenience header: boost/asio.hpp

Open the socket using the specified protocol.

void open(
    const protocol_type & protocol = protocol_type());
  » more...

boost::system::error_code open(
    const protocol_type & protocol,
    boost::system::error_code & ec);
  » more...

Open the socket using the specified protocol.

void open(
    const protocol_type & protocol = protocol_type());

This function opens the socket so that it will use the specified protocol.

Parameters

protocol

An object specifying protocol parameters to be used.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::socket socket(io_service);
socket.open(boost::asio::ip::tcp::v4());

Open the socket using the specified protocol.

boost::system::error_code open(
    const protocol_type & protocol,
    boost::system::error_code & ec);

This function opens the socket so that it will use the specified protocol.

Parameters

protocol

An object specifying which protocol is to be used.

ec

Set to indicate what error occurred, if any.

Example
boost::asio::ip::tcp::socket socket(io_service);
boost::system::error_code ec;
socket.open(boost::asio::ip::tcp::v4(), ec);
if (ec)
{
  // An error occurred.
}

Move-assign a basic_socket from another.

basic_socket & operator=(
    basic_socket && other);
  » more...

Move-assign a basic_socket from a socket of another protocol type.

template<
    typename Protocol1,
    typename SocketService1>
enable_if< is_convertible< Protocol1, Protocol >::value, basic_socket >::type & operator=(
    basic_socket< Protocol1, SocketService1 > && other);
  » more...

Move-assign a basic_socket from another.

basic_socket & operator=(
    basic_socket && other);

This assignment operator moves a socket from one object to another.

Parameters

other

The other basic_socket object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_socket(io_service&) constructor.

Move-assign a basic_socket from a socket of another protocol type.

template<
    typename Protocol1,
    typename SocketService1>
enable_if< is_convertible< Protocol1, Protocol >::value, basic_socket >::type & operator=(
    basic_socket< Protocol1, SocketService1 > && other);

This assignment operator moves a socket from one object to another.

Parameters

other

The other basic_socket object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_socket(io_service&) constructor.

The protocol type.

typedef Protocol protocol_type;
Requirements

Header: boost/asio/basic_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option for the receive buffer size of a socket.

typedef implementation_defined receive_buffer_size;

Implements the SOL_SOCKET/SO_RCVBUF socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_buffer_size option(8192);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_buffer_size option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/basic_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option for the receive low watermark.

typedef implementation_defined receive_low_watermark;

Implements the SOL_SOCKET/SO_RCVLOWAT socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_low_watermark option(1024);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_low_watermark option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/basic_socket.hpp

Convenience header: boost/asio.hpp

Get the remote endpoint of the socket.

endpoint_type remote_endpoint() const;
  » more...

endpoint_type remote_endpoint(
    boost::system::error_code & ec) const;
  » more...

Get the remote endpoint of the socket.

endpoint_type remote_endpoint() const;

This function is used to obtain the remote endpoint of the socket.

Return Value

An object that represents the remote endpoint of the socket.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::endpoint endpoint = socket.remote_endpoint();

Get the remote endpoint of the socket.

endpoint_type remote_endpoint(
    boost::system::error_code & ec) const;

This function is used to obtain the remote endpoint of the socket.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

An object that represents the remote endpoint of the socket. Returns a default-constructed endpoint object if an error occurred.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::system::error_code ec;
boost::asio::ip::tcp::endpoint endpoint = socket.remote_endpoint(ec);
if (ec)
{
  // An error occurred.
}

Inherited from socket_base.

Socket option to allow the socket to be bound to an address that is already in use.

typedef implementation_defined reuse_address;

Implements the SOL_SOCKET/SO_REUSEADDR socket option.

Examples

Setting the option:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::reuse_address option(true);
acceptor.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::reuse_address option;
acceptor.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option for the send buffer size of a socket.

typedef implementation_defined send_buffer_size;

Implements the SOL_SOCKET/SO_SNDBUF socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_buffer_size option(8192);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_buffer_size option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/basic_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option for the send low watermark.

typedef implementation_defined send_low_watermark;

Implements the SOL_SOCKET/SO_SNDLOWAT socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_low_watermark option(1024);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_low_watermark option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/basic_socket.hpp

Convenience header: boost/asio.hpp

Inherited from basic_io_object.

(Deprecated: Use get_service().) The service associated with the I/O object.

service_type & service;
Remarks

Available only for services that do not support movability.

Inherited from basic_io_object.

The type of the service that will be used to provide I/O operations.

typedef SocketService service_type;
Requirements

Header: boost/asio/basic_socket.hpp

Convenience header: boost/asio.hpp

Set an option on the socket.

template<
    typename SettableSocketOption>
void set_option(
    const SettableSocketOption & option);
  » more...

template<
    typename SettableSocketOption>
boost::system::error_code set_option(
    const SettableSocketOption & option,
    boost::system::error_code & ec);
  » more...

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.

Parameters

option

The new option value to be set on the socket.

Exceptions

boost::system::system_error

Thrown on failure.

Example

Setting the IPPROTO_TCP/TCP_NODELAY option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::no_delay option(true);
socket.set_option(option);

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.

Parameters

option

The new option value to be set on the socket.

ec

Set to indicate what error occurred, if any.

Example

Setting the IPPROTO_TCP/TCP_NODELAY option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::no_delay option(true);
boost::system::error_code ec;
socket.set_option(option, ec);
if (ec)
{
  // An error occurred.
}

Disable sends or receives on the socket.

void shutdown(
    shutdown_type what);
  » more...

boost::system::error_code shutdown(
    shutdown_type what,
    boost::system::error_code & ec);
  » more...

Disable sends or receives on the socket.

void shutdown(
    shutdown_type what);

This function is used to disable send operations, receive operations, or both.

Parameters

what

Determines what types of operation will no longer be allowed.

Exceptions

boost::system::system_error

Thrown on failure.

Example

Shutting down the send side of the socket:

boost::asio::ip::tcp::socket socket(io_service);
...
socket.shutdown(boost::asio::ip::tcp::socket::shutdown_send);

Disable sends or receives on the socket.

boost::system::error_code shutdown(
    shutdown_type what,
    boost::system::error_code & ec);

This function is used to disable send operations, receive operations, or both.

Parameters

what

Determines what types of operation will no longer be allowed.

ec

Set to indicate what error occurred, if any.

Example

Shutting down the send side of the socket:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::system::error_code ec;
socket.shutdown(boost::asio::ip::tcp::socket::shutdown_send, ec);
if (ec)
{
  // An error occurred.
}

Inherited from socket_base.

Different ways a socket may be shutdown.

enum shutdown_type

Values

shutdown_receive

Shutdown the receive side of the socket.

shutdown_send

Shutdown the send side of the socket.

shutdown_both

Shutdown both send and receive on the socket.

Protected destructor to prevent deletion through this type.

~basic_socket();
basic_socket_acceptor::accept
basic_socket_acceptor::assign
basic_socket_acceptor::async_accept
basic_socket_acceptor::basic_socket_acceptor
basic_socket_acceptor::bind
basic_socket_acceptor::broadcast
basic_socket_acceptor::bytes_readable
basic_socket_acceptor::cancel
basic_socket_acceptor::close
basic_socket_acceptor::debug
basic_socket_acceptor::do_not_route
basic_socket_acceptor::enable_connection_aborted
basic_socket_acceptor::endpoint_type
basic_socket_acceptor::get_implementation
basic_socket_acceptor::get_io_service
basic_socket_acceptor::get_option
basic_socket_acceptor::get_service
basic_socket_acceptor::implementation
basic_socket_acceptor::implementation_type
basic_socket_acceptor::io_control
basic_socket_acceptor::is_open
basic_socket_acceptor::keep_alive
basic_socket_acceptor::linger
basic_socket_acceptor::listen
basic_socket_acceptor::local_endpoint
basic_socket_acceptor::max_connections
basic_socket_acceptor::message_do_not_route
basic_socket_acceptor::message_end_of_record
basic_socket_acceptor::message_flags
basic_socket_acceptor::message_out_of_band
basic_socket_acceptor::message_peek
basic_socket_acceptor::native
basic_socket_acceptor::native_handle
basic_socket_acceptor::native_handle_type
basic_socket_acceptor::native_non_blocking
basic_socket_acceptor::native_type
basic_socket_acceptor::non_blocking
basic_socket_acceptor::non_blocking_io
basic_socket_acceptor::open
basic_socket_acceptor::operator=
basic_socket_acceptor::protocol_type
basic_socket_acceptor::receive_buffer_size
basic_socket_acceptor::receive_low_watermark
basic_socket_acceptor::reuse_address
basic_socket_acceptor::send_buffer_size
basic_socket_acceptor::send_low_watermark
basic_socket_acceptor::service
basic_socket_acceptor::service_type
basic_socket_acceptor::set_option
basic_socket_acceptor::shutdown_type

Provides the ability to accept new connections.

template<
    typename Protocol,
    typename SocketAcceptorService = socket_acceptor_service<Protocol>>
class basic_socket_acceptor :
  public basic_io_object< SocketAcceptorService >,
  public socket_base
Types

Name

Description

broadcast

Socket option to permit sending of broadcast messages.

bytes_readable

IO control command to get the amount of data that can be read without blocking.

debug

Socket option to enable socket-level debugging.

do_not_route

Socket option to prevent routing, use local interfaces only.

enable_connection_aborted

Socket option to report aborted connections on accept.

endpoint_type

The endpoint type.

implementation_type

The underlying implementation type of I/O object.

keep_alive

Socket option to send keep-alives.

linger

Socket option to specify whether the socket lingers on close if unsent data is present.

message_flags

Bitmask type for flags that can be passed to send and receive operations.

native_handle_type

The native representation of an acceptor.

native_type

(Deprecated: Use native_handle_type.) The native representation of an acceptor.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

protocol_type

The protocol type.

receive_buffer_size

Socket option for the receive buffer size of a socket.

receive_low_watermark

Socket option for the receive low watermark.

reuse_address

Socket option to allow the socket to be bound to an address that is already in use.

send_buffer_size

Socket option for the send buffer size of a socket.

send_low_watermark

Socket option for the send low watermark.

service_type

The type of the service that will be used to provide I/O operations.

shutdown_type

Different ways a socket may be shutdown.

Member Functions

Name

Description

accept

Accept a new connection.

Accept a new connection and obtain the endpoint of the peer.

assign

Assigns an existing native acceptor to the acceptor.

async_accept

Start an asynchronous accept.

basic_socket_acceptor

Construct an acceptor without opening it.

Construct an open acceptor.

Construct an acceptor opened on the given endpoint.

Construct a basic_socket_acceptor on an existing native acceptor.

Move-construct a basic_socket_acceptor from another.

Move-construct a basic_socket_acceptor from an acceptor of another protocol type.

bind

Bind the acceptor to the given local endpoint.

cancel

Cancel all asynchronous operations associated with the acceptor.

close

Close the acceptor.

get_io_service

Get the io_service associated with the object.

get_option

Get an option from the acceptor.

io_control

Perform an IO control command on the acceptor.

is_open

Determine whether the acceptor is open.

listen

Place the acceptor into the state where it will listen for new connections.

local_endpoint

Get the local endpoint of the acceptor.

native

(Deprecated: Use native_handle().) Get the native acceptor representation.

native_handle

Get the native acceptor representation.

native_non_blocking

Gets the non-blocking mode of the native acceptor implementation.

Sets the non-blocking mode of the native acceptor implementation.

non_blocking

Gets the non-blocking mode of the acceptor.

Sets the non-blocking mode of the acceptor.

open

Open the acceptor using the specified protocol.

operator=

Move-assign a basic_socket_acceptor from another.

Move-assign a basic_socket_acceptor from an acceptor of another protocol type.

set_option

Set an option on the acceptor.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Data Members

Name

Description

max_connections

The maximum length of the queue of pending incoming connections.

message_do_not_route

Specify that the data should not be subject to routing.

message_end_of_record

Specifies that the data marks the end of a record.

message_out_of_band

Process out-of-band data.

message_peek

Peek at incoming data without removing it from the input queue.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_socket_acceptor class template is used for accepting new socket connections.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Example

Opening a socket acceptor with the SO_REUSEADDR option enabled:

boost::asio::ip::tcp::acceptor acceptor(io_service);
boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), port);
acceptor.open(endpoint.protocol());
acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor.bind(endpoint);
acceptor.listen();
Requirements

Header: boost/asio/basic_socket_acceptor.hpp

Convenience header: boost/asio.hpp

Accept a new connection.

template<
    typename Protocol1,
    typename SocketService>
void accept(
    basic_socket< Protocol1, SocketService > & peer,
    typename enable_if< is_convertible< Protocol, Protocol1 >::value >::type *  = 0);
  » more...

template<
    typename Protocol1,
    typename SocketService>
boost::system::error_code accept(
    basic_socket< Protocol1, SocketService > & peer,
    boost::system::error_code & ec,
    typename enable_if< is_convertible< Protocol, Protocol1 >::value >::type *  = 0);
  » more...

Accept a new connection and obtain the endpoint of the peer.

template<
    typename SocketService>
void accept(
    basic_socket< protocol_type, SocketService > & peer,
    endpoint_type & peer_endpoint);
  » more...

template<
    typename SocketService>
boost::system::error_code accept(
    basic_socket< protocol_type, SocketService > & peer,
    endpoint_type & peer_endpoint,
    boost::system::error_code & ec);
  » more...

Accept a new connection.

template<
    typename Protocol1,
    typename SocketService>
void accept(
    basic_socket< Protocol1, SocketService > & peer,
    typename enable_if< is_convertible< Protocol, Protocol1 >::value >::type *  = 0);

This function is used to accept a new connection from a peer into the given socket. The function call will block until a new connection has been accepted successfully or an error occurs.

Parameters

peer

The socket into which the new connection will be accepted.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::ip::tcp::socket socket(io_service);
acceptor.accept(socket);

Accept a new connection.

template<
    typename Protocol1,
    typename SocketService>
boost::system::error_code accept(
    basic_socket< Protocol1, SocketService > & peer,
    boost::system::error_code & ec,
    typename enable_if< is_convertible< Protocol, Protocol1 >::value >::type *  = 0);

This function is used to accept a new connection from a peer into the given socket. The function call will block until a new connection has been accepted successfully or an error occurs.

Parameters

peer

The socket into which the new connection will be accepted.

ec

Set to indicate what error occurred, if any.

Example
boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::ip::tcp::soocket socket(io_service);
boost::system::error_code ec;
acceptor.accept(socket, ec);
if (ec)
{
  // An error occurred.
}

Accept a new connection and obtain the endpoint of the peer.

template<
    typename SocketService>
void accept(
    basic_socket< protocol_type, SocketService > & peer,
    endpoint_type & peer_endpoint);

This function is used to accept a new connection from a peer into the given socket, and additionally provide the endpoint of the remote peer. The function call will block until a new connection has been accepted successfully or an error occurs.

Parameters

peer

The socket into which the new connection will be accepted.

peer_endpoint

An endpoint object which will receive the endpoint of the remote peer.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::ip::tcp::socket socket(io_service);
boost::asio::ip::tcp::endpoint endpoint;
acceptor.accept(socket, endpoint);

Accept a new connection and obtain the endpoint of the peer.

template<
    typename SocketService>
boost::system::error_code accept(
    basic_socket< protocol_type, SocketService > & peer,
    endpoint_type & peer_endpoint,
    boost::system::error_code & ec);

This function is used to accept a new connection from a peer into the given socket, and additionally provide the endpoint of the remote peer. The function call will block until a new connection has been accepted successfully or an error occurs.

Parameters

peer

The socket into which the new connection will be accepted.

peer_endpoint

An endpoint object which will receive the endpoint of the remote peer.

ec

Set to indicate what error occurred, if any.

Example
boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::ip::tcp::socket socket(io_service);
boost::asio::ip::tcp::endpoint endpoint;
boost::system::error_code ec;
acceptor.accept(socket, endpoint, ec);
if (ec)
{
  // An error occurred.
}

Assigns an existing native acceptor to the acceptor.

void assign(
    const protocol_type & protocol,
    const native_handle_type & native_acceptor);
  » more...

boost::system::error_code assign(
    const protocol_type & protocol,
    const native_handle_type & native_acceptor,
    boost::system::error_code & ec);
  » more...

Assigns an existing native acceptor to the acceptor.

void assign(
    const protocol_type & protocol,
    const native_handle_type & native_acceptor);

Assigns an existing native acceptor to the acceptor.

boost::system::error_code assign(
    const protocol_type & protocol,
    const native_handle_type & native_acceptor,
    boost::system::error_code & ec);

Start an asynchronous accept.

template<
    typename Protocol1,
    typename SocketService,
    typename AcceptHandler>
void-or-deduced async_accept(
    basic_socket< Protocol1, SocketService > & peer,
    AcceptHandler handler,
    typename enable_if< is_convertible< Protocol, Protocol1 >::value >::type *  = 0);
  » more...

template<
    typename SocketService,
    typename AcceptHandler>
void-or-deduced async_accept(
    basic_socket< protocol_type, SocketService > & peer,
    endpoint_type & peer_endpoint,
    AcceptHandler handler);
  » more...

Start an asynchronous accept.

template<
    typename Protocol1,
    typename SocketService,
    typename AcceptHandler>
void-or-deduced async_accept(
    basic_socket< Protocol1, SocketService > & peer,
    AcceptHandler handler,
    typename enable_if< is_convertible< Protocol, Protocol1 >::value >::type *  = 0);

This function is used to asynchronously accept a new connection into a socket. The function call always returns immediately.

Parameters

peer

The socket into which the new connection will be accepted. Ownership of the peer object is retained by the caller, which must guarantee that it is valid until the handler is called.

handler

The handler to be called when the accept operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error // Result of operation.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Example
void accept_handler(const boost::system::error_code& error)
{
  if (!error)
  {
    // Accept succeeded.
  }
}

...

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::ip::tcp::socket socket(io_service);
acceptor.async_accept(socket, accept_handler);

Start an asynchronous accept.

template<
    typename SocketService,
    typename AcceptHandler>
void-or-deduced async_accept(
    basic_socket< protocol_type, SocketService > & peer,
    endpoint_type & peer_endpoint,
    AcceptHandler handler);

This function is used to asynchronously accept a new connection into a socket, and additionally obtain the endpoint of the remote peer. The function call always returns immediately.

Parameters

peer

The socket into which the new connection will be accepted. Ownership of the peer object is retained by the caller, which must guarantee that it is valid until the handler is called.

peer_endpoint

An endpoint object into which the endpoint of the remote peer will be written. Ownership of the peer_endpoint object is retained by the caller, which must guarantee that it is valid until the handler is called.

handler

The handler to be called when the accept operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error // Result of operation.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Construct an acceptor without opening it.

explicit basic_socket_acceptor(
    boost::asio::io_service & io_service);
  » more...

Construct an open acceptor.

basic_socket_acceptor(
    boost::asio::io_service & io_service,
    const protocol_type & protocol);
  » more...

Construct an acceptor opened on the given endpoint.

basic_socket_acceptor(
    boost::asio::io_service & io_service,
    const endpoint_type & endpoint,
    bool reuse_addr = true);
  » more...

Construct a basic_socket_acceptor on an existing native acceptor.

basic_socket_acceptor(
    boost::asio::io_service & io_service,
    const protocol_type & protocol,
    const native_handle_type & native_acceptor);
  » more...

Move-construct a basic_socket_acceptor from another.

basic_socket_acceptor(
    basic_socket_acceptor && other);
  » more...

Move-construct a basic_socket_acceptor from an acceptor of another protocol type.

template<
    typename Protocol1,
    typename SocketAcceptorService1>
basic_socket_acceptor(
    basic_socket_acceptor< Protocol1, SocketAcceptorService1 > && other,
    typename enable_if< is_convertible< Protocol1, Protocol >::value >::type *  = 0);
  » more...

Construct an acceptor without opening it.

basic_socket_acceptor(
    boost::asio::io_service & io_service);

This constructor creates an acceptor without opening it to listen for new connections. The open() function must be called before the acceptor can accept new socket connections.

Parameters

io_service

The io_service object that the acceptor will use to dispatch handlers for any asynchronous operations performed on the acceptor.

Construct an open acceptor.

basic_socket_acceptor(
    boost::asio::io_service & io_service,
    const protocol_type & protocol);

This constructor creates an acceptor and automatically opens it.

Parameters

io_service

The io_service object that the acceptor will use to dispatch handlers for any asynchronous operations performed on the acceptor.

protocol

An object specifying protocol parameters to be used.

Exceptions

boost::system::system_error

Thrown on failure.

Construct an acceptor opened on the given endpoint.

basic_socket_acceptor(
    boost::asio::io_service & io_service,
    const endpoint_type & endpoint,
    bool reuse_addr = true);

This constructor creates an acceptor and automatically opens it to listen for new connections on the specified endpoint.

Parameters

io_service

The io_service object that the acceptor will use to dispatch handlers for any asynchronous operations performed on the acceptor.

endpoint

An endpoint on the local machine on which the acceptor will listen for new connections.

reuse_addr

Whether the constructor should set the socket option socket_base::reuse_address.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

This constructor is equivalent to the following code:

basic_socket_acceptor<Protocol> acceptor(io_service);
acceptor.open(endpoint.protocol());
if (reuse_addr)
  acceptor.set_option(socket_base::reuse_address(true));
acceptor.bind(endpoint);
acceptor.listen(listen_backlog);

Construct a basic_socket_acceptor on an existing native acceptor.

basic_socket_acceptor(
    boost::asio::io_service & io_service,
    const protocol_type & protocol,
    const native_handle_type & native_acceptor);

This constructor creates an acceptor object to hold an existing native acceptor.

Parameters

io_service

The io_service object that the acceptor will use to dispatch handlers for any asynchronous operations performed on the acceptor.

protocol

An object specifying protocol parameters to be used.

native_acceptor

A native acceptor.

Exceptions

boost::system::system_error

Thrown on failure.

Move-construct a basic_socket_acceptor from another.

basic_socket_acceptor(
    basic_socket_acceptor && other);

This constructor moves an acceptor from one object to another.

Parameters

other

The other basic_socket_acceptor object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_socket_acceptor(io_service&) constructor.

Move-construct a basic_socket_acceptor from an acceptor of another protocol type.

template<
    typename Protocol1,
    typename SocketAcceptorService1>
basic_socket_acceptor(
    basic_socket_acceptor< Protocol1, SocketAcceptorService1 > && other,
    typename enable_if< is_convertible< Protocol1, Protocol >::value >::type *  = 0);

This constructor moves an acceptor from one object to another.

Parameters

other

The other basic_socket_acceptor object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_socket(io_service&) constructor.

Bind the acceptor to the given local endpoint.

void bind(
    const endpoint_type & endpoint);
  » more...

boost::system::error_code bind(
    const endpoint_type & endpoint,
    boost::system::error_code & ec);
  » more...

Bind the acceptor to the given local endpoint.

void bind(
    const endpoint_type & endpoint);

This function binds the socket acceptor to the specified endpoint on the local machine.

Parameters

endpoint

An endpoint on the local machine to which the socket acceptor will be bound.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::acceptor acceptor(io_service);
boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), 12345);
acceptor.open(endpoint.protocol());
acceptor.bind(endpoint);

Bind the acceptor to the given local endpoint.

boost::system::error_code bind(
    const endpoint_type & endpoint,
    boost::system::error_code & ec);

This function binds the socket acceptor to the specified endpoint on the local machine.

Parameters

endpoint

An endpoint on the local machine to which the socket acceptor will be bound.

ec

Set to indicate what error occurred, if any.

Example
boost::asio::ip::tcp::acceptor acceptor(io_service);
boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), 12345);
acceptor.open(endpoint.protocol());
boost::system::error_code ec;
acceptor.bind(endpoint, ec);
if (ec)
{
  // An error occurred.
}

Inherited from socket_base.

Socket option to permit sending of broadcast messages.

typedef implementation_defined broadcast;

Implements the SOL_SOCKET/SO_BROADCAST socket option.

Examples

Setting the option:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::broadcast option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::broadcast option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_socket_acceptor.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

IO control command to get the amount of data that can be read without blocking.

typedef implementation_defined bytes_readable;

Implements the FIONREAD IO control command.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::bytes_readable command(true);
socket.io_control(command);
std::size_t bytes_readable = command.get();
Requirements

Header: boost/asio/basic_socket_acceptor.hpp

Convenience header: boost/asio.hpp

Cancel all asynchronous operations associated with the acceptor.

void cancel();
  » more...

boost::system::error_code cancel(
    boost::system::error_code & ec);
  » more...

Cancel all asynchronous operations associated with the acceptor.

void cancel();

This function causes all outstanding asynchronous connect, send and receive operations to finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error.

Exceptions

boost::system::system_error

Thrown on failure.

Cancel all asynchronous operations associated with the acceptor.

boost::system::error_code cancel(
    boost::system::error_code & ec);

This function causes all outstanding asynchronous connect, send and receive operations to finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error.

Parameters

ec

Set to indicate what error occurred, if any.

Close the acceptor.

void close();
  » more...

boost::system::error_code close(
    boost::system::error_code & ec);
  » more...

Close the acceptor.

void close();

This function is used to close the acceptor. Any asynchronous accept operations will be cancelled immediately.

A subsequent call to open() is required before the acceptor can again be used to again perform socket accept operations.

Exceptions

boost::system::system_error

Thrown on failure.

Close the acceptor.

boost::system::error_code close(
    boost::system::error_code & ec);

This function is used to close the acceptor. Any asynchronous accept operations will be cancelled immediately.

A subsequent call to open() is required before the acceptor can again be used to again perform socket accept operations.

Parameters

ec

Set to indicate what error occurred, if any.

Example
boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::system::error_code ec;
acceptor.close(ec);
if (ec)
{
  // An error occurred.
}

Inherited from socket_base.

Socket option to enable socket-level debugging.

typedef implementation_defined debug;

Implements the SOL_SOCKET/SO_DEBUG socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::debug option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::debug option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_socket_acceptor.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option to prevent routing, use local interfaces only.

typedef implementation_defined do_not_route;

Implements the SOL_SOCKET/SO_DONTROUTE socket option.

Examples

Setting the option:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::do_not_route option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::do_not_route option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_socket_acceptor.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option to report aborted connections on accept.

typedef implementation_defined enable_connection_aborted;

Implements a custom socket option that determines whether or not an accept operation is permitted to fail with boost::asio::error::connection_aborted. By default the option is false.

Examples

Setting the option:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::enable_connection_aborted option(true);
acceptor.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::enable_connection_aborted option;
acceptor.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_socket_acceptor.hpp

Convenience header: boost/asio.hpp

The endpoint type.

typedef Protocol::endpoint endpoint_type;
Requirements

Header: boost/asio/basic_socket_acceptor.hpp

Convenience header: boost/asio.hpp

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();
  » more...

const implementation_type & get_implementation() const;
  » more...

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

const implementation_type & get_implementation() const;

Inherited from basic_io_object.

Get the io_service associated with the object.

boost::asio::io_service & get_io_service();

This function may be used to obtain the io_service object that the I/O object uses to dispatch handlers for asynchronous operations.

Return Value

A reference to the io_service object that the I/O object will use to dispatch handlers. Ownership is not transferred to the caller.

Get an option from the acceptor.

template<
    typename GettableSocketOption>
void get_option(
    GettableSocketOption & option);
  » more...

template<
    typename GettableSocketOption>
boost::system::error_code get_option(
    GettableSocketOption & option,
    boost::system::error_code & ec);
  » more...

Get an option from the acceptor.

template<
    typename GettableSocketOption>
void get_option(
    GettableSocketOption & option);

This function is used to get the current value of an option on the acceptor.

Parameters

option

The option value to be obtained from the acceptor.

Exceptions

boost::system::system_error

Thrown on failure.

Example

Getting the value of the SOL_SOCKET/SO_REUSEADDR option:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::ip::tcp::acceptor::reuse_address option;
acceptor.get_option(option);
bool is_set = option.get();

Get an option from the acceptor.

template<
    typename GettableSocketOption>
boost::system::error_code get_option(
    GettableSocketOption & option,
    boost::system::error_code & ec);

This function is used to get the current value of an option on the acceptor.

Parameters

option

The option value to be obtained from the acceptor.

ec

Set to indicate what error occurred, if any.

Example

Getting the value of the SOL_SOCKET/SO_REUSEADDR option:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::ip::tcp::acceptor::reuse_address option;
boost::system::error_code ec;
acceptor.get_option(option, ec);
if (ec)
{
  // An error occurred.
}
bool is_set = option.get();

Get the service associated with the I/O object.

service_type & get_service();
  » more...

const service_type & get_service() const;
  » more...

Inherited from basic_io_object.

Get the service associated with the I/O object.

service_type & get_service();

Inherited from basic_io_object.

Get the service associated with the I/O object.

const service_type & get_service() const;

Inherited from basic_io_object.

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

implementation_type implementation;

Inherited from basic_io_object.

The underlying implementation type of I/O object.

typedef service_type::implementation_type implementation_type;
Requirements

Header: boost/asio/basic_socket_acceptor.hpp

Convenience header: boost/asio.hpp

Perform an IO control command on the acceptor.

template<
    typename IoControlCommand>
void io_control(
    IoControlCommand & command);
  » more...

template<
    typename IoControlCommand>
boost::system::error_code io_control(
    IoControlCommand & command,
    boost::system::error_code & ec);
  » more...

Perform an IO control command on the acceptor.

template<
    typename IoControlCommand>
void io_control(
    IoControlCommand & command);

This function is used to execute an IO control command on the acceptor.

Parameters

command

The IO control command to be performed on the acceptor.

Exceptions

boost::system::system_error

Thrown on failure.

Example

Getting the number of bytes ready to read:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::ip::tcp::acceptor::non_blocking_io command(true);
socket.io_control(command);

Perform an IO control command on the acceptor.

template<
    typename IoControlCommand>
boost::system::error_code io_control(
    IoControlCommand & command,
    boost::system::error_code & ec);

This function is used to execute an IO control command on the acceptor.

Parameters

command

The IO control command to be performed on the acceptor.

ec

Set to indicate what error occurred, if any.

Example

Getting the number of bytes ready to read:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::ip::tcp::acceptor::non_blocking_io command(true);
boost::system::error_code ec;
socket.io_control(command, ec);
if (ec)
{
  // An error occurred.
}

Determine whether the acceptor is open.

bool is_open() const;

Inherited from socket_base.

Socket option to send keep-alives.

typedef implementation_defined keep_alive;

Implements the SOL_SOCKET/SO_KEEPALIVE socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::keep_alive option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::keep_alive option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_socket_acceptor.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

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.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::linger option(true, 30);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::linger option;
socket.get_option(option);
bool is_set = option.enabled();
unsigned short timeout = option.timeout();
Requirements

Header: boost/asio/basic_socket_acceptor.hpp

Convenience header: boost/asio.hpp

Place the acceptor into the state where it will listen for new connections.

void listen(
    int backlog = socket_base::max_connections);
  » more...

boost::system::error_code listen(
    int backlog,
    boost::system::error_code & ec);
  » more...

Place the acceptor into the state where it will listen for new connections.

void listen(
    int backlog = socket_base::max_connections);

This function puts the socket acceptor into the state where it may accept new connections.

Parameters

backlog

The maximum length of the queue of pending connections.

Exceptions

boost::system::system_error

Thrown on failure.

Place the acceptor into the state where it will listen for new connections.

boost::system::error_code listen(
    int backlog,
    boost::system::error_code & ec);

This function puts the socket acceptor into the state where it may accept new connections.

Parameters

backlog

The maximum length of the queue of pending connections.

ec

Set to indicate what error occurred, if any.

Example
boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::system::error_code ec;
acceptor.listen(boost::asio::socket_base::max_connections, ec);
if (ec)
{
  // An error occurred.
}

Get the local endpoint of the acceptor.

endpoint_type local_endpoint() const;
  » more...

endpoint_type local_endpoint(
    boost::system::error_code & ec) const;
  » more...

Get the local endpoint of the acceptor.

endpoint_type local_endpoint() const;

This function is used to obtain the locally bound endpoint of the acceptor.

Return Value

An object that represents the local endpoint of the acceptor.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::ip::tcp::endpoint endpoint = acceptor.local_endpoint();

Get the local endpoint of the acceptor.

endpoint_type local_endpoint(
    boost::system::error_code & ec) const;

This function is used to obtain the locally bound endpoint of the acceptor.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

An object that represents the local endpoint of the acceptor. Returns a default-constructed endpoint object if an error occurred and the error handler did not throw an exception.

Example
boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::system::error_code ec;
boost::asio::ip::tcp::endpoint endpoint = acceptor.local_endpoint(ec);
if (ec)
{
  // An error occurred.
}

Inherited from socket_base.

The maximum length of the queue of pending incoming connections.

static const int max_connections = implementation_defined;

Inherited from socket_base.

Specify that the data should not be subject to routing.

static const int message_do_not_route = implementation_defined;

Inherited from socket_base.

Specifies that the data marks the end of a record.

static const int message_end_of_record = implementation_defined;

Inherited from socket_base.

Bitmask type for flags that can be passed to send and receive operations.

typedef int message_flags;
Requirements

Header: boost/asio/basic_socket_acceptor.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Process out-of-band data.

static const int message_out_of_band = implementation_defined;

Inherited from socket_base.

Peek at incoming data without removing it from the input queue.

static const int message_peek = implementation_defined;

(Deprecated: Use native_handle().) Get the native acceptor representation.

native_type native();

This function may be used to obtain the underlying representation of the acceptor. This is intended to allow access to native acceptor functionality that is not otherwise provided.

Get the native acceptor representation.

native_handle_type native_handle();

This function may be used to obtain the underlying representation of the acceptor. This is intended to allow access to native acceptor functionality that is not otherwise provided.

The native representation of an acceptor.

typedef SocketAcceptorService::native_handle_type native_handle_type;
Requirements

Header: boost/asio/basic_socket_acceptor.hpp

Convenience header: boost/asio.hpp

Gets the non-blocking mode of the native acceptor implementation.

bool native_non_blocking() const;
  » more...

Sets the non-blocking mode of the native acceptor implementation.

void native_non_blocking(
    bool mode);
  » more...

boost::system::error_code native_non_blocking(
    bool mode,
    boost::system::error_code & ec);
  » more...

Gets the non-blocking mode of the native acceptor implementation.

bool native_non_blocking() const;

This function is used to retrieve the non-blocking mode of the underlying native acceptor. This mode has no effect on the behaviour of the acceptor object's synchronous operations.

Return Value

true if the underlying acceptor is in non-blocking mode and direct system calls may fail with boost::asio::error::would_block (or the equivalent system error).

Remarks

The current non-blocking mode is cached by the acceptor object. Consequently, the return value may be incorrect if the non-blocking mode was set directly on the native acceptor.

Sets the non-blocking mode of the native acceptor implementation.

void native_non_blocking(
    bool mode);

This function is used to modify the non-blocking mode of the underlying native acceptor. It has no effect on the behaviour of the acceptor object's synchronous operations.

Parameters

mode

If true, the underlying acceptor is put into non-blocking mode and direct system calls may fail with boost::asio::error::would_block (or the equivalent system error).

Exceptions

boost::system::system_error

Thrown on failure. If the mode is false, but the current value of non_blocking() is true, this function fails with boost::asio::error::invalid_argument, as the combination does not make sense.

Sets the non-blocking mode of the native acceptor implementation.

boost::system::error_code native_non_blocking(
    bool mode,
    boost::system::error_code & ec);

This function is used to modify the non-blocking mode of the underlying native acceptor. It has no effect on the behaviour of the acceptor object's synchronous operations.

Parameters

mode

If true, the underlying acceptor is put into non-blocking mode and direct system calls may fail with boost::asio::error::would_block (or the equivalent system error).

ec

Set to indicate what error occurred, if any. If the mode is false, but the current value of non_blocking() is true, this function fails with boost::asio::error::invalid_argument, as the combination does not make sense.

(Deprecated: Use native_handle_type.) The native representation of an acceptor.

typedef SocketAcceptorService::native_handle_type native_type;
Requirements

Header: boost/asio/basic_socket_acceptor.hpp

Convenience header: boost/asio.hpp

Gets the non-blocking mode of the acceptor.

bool non_blocking() const;
  » more...

Sets the non-blocking mode of the acceptor.

void non_blocking(
    bool mode);
  » more...

boost::system::error_code non_blocking(
    bool mode,
    boost::system::error_code & ec);
  » more...

Gets the non-blocking mode of the acceptor.

bool non_blocking() const;
Return Value

true if the acceptor's synchronous operations will fail with boost::asio::error::would_block if they are unable to perform the requested operation immediately. If false, synchronous operations will block until complete.

Remarks

The non-blocking mode has no effect on the behaviour of asynchronous operations. Asynchronous operations will never fail with the error boost::asio::error::would_block.

Sets the non-blocking mode of the acceptor.

void non_blocking(
    bool mode);
Parameters

mode

If true, the acceptor's synchronous operations will fail with boost::asio::error::would_block if they are unable to perform the requested operation immediately. If false, synchronous operations will block until complete.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

The non-blocking mode has no effect on the behaviour of asynchronous operations. Asynchronous operations will never fail with the error boost::asio::error::would_block.

Sets the non-blocking mode of the acceptor.

boost::system::error_code non_blocking(
    bool mode,
    boost::system::error_code & ec);
Parameters

mode

If true, the acceptor's synchronous operations will fail with boost::asio::error::would_block if they are unable to perform the requested operation immediately. If false, synchronous operations will block until complete.

ec

Set to indicate what error occurred, if any.

Remarks

The non-blocking mode has no effect on the behaviour of asynchronous operations. Asynchronous operations will never fail with the error boost::asio::error::would_block.

Inherited from socket_base.

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

typedef implementation_defined non_blocking_io;

Implements the FIONBIO IO control command.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::non_blocking_io command(true);
socket.io_control(command);
Requirements

Header: boost/asio/basic_socket_acceptor.hpp

Convenience header: boost/asio.hpp

Open the acceptor using the specified protocol.

void open(
    const protocol_type & protocol = protocol_type());
  » more...

boost::system::error_code open(
    const protocol_type & protocol,
    boost::system::error_code & ec);
  » more...

Open the acceptor using the specified protocol.

void open(
    const protocol_type & protocol = protocol_type());

This function opens the socket acceptor so that it will use the specified protocol.

Parameters

protocol

An object specifying which protocol is to be used.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::acceptor acceptor(io_service);
acceptor.open(boost::asio::ip::tcp::v4());

Open the acceptor using the specified protocol.

boost::system::error_code open(
    const protocol_type & protocol,
    boost::system::error_code & ec);

This function opens the socket acceptor so that it will use the specified protocol.

Parameters

protocol

An object specifying which protocol is to be used.

ec

Set to indicate what error occurred, if any.

Example
boost::asio::ip::tcp::acceptor acceptor(io_service);
boost::system::error_code ec;
acceptor.open(boost::asio::ip::tcp::v4(), ec);
if (ec)
{
  // An error occurred.
}

Move-assign a basic_socket_acceptor from another.

basic_socket_acceptor & operator=(
    basic_socket_acceptor && other);
  » more...

Move-assign a basic_socket_acceptor from an acceptor of another protocol type.

template<
    typename Protocol1,
    typename SocketAcceptorService1>
enable_if< is_convertible< Protocol1, Protocol >::value, basic_socket_acceptor >::type & operator=(
    basic_socket_acceptor< Protocol1, SocketAcceptorService1 > && other);
  » more...

Move-assign a basic_socket_acceptor from another.

basic_socket_acceptor & operator=(
    basic_socket_acceptor && other);

This assignment operator moves an acceptor from one object to another.

Parameters

other

The other basic_socket_acceptor object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_socket_acceptor(io_service&) constructor.

Move-assign a basic_socket_acceptor from an acceptor of another protocol type.

template<
    typename Protocol1,
    typename SocketAcceptorService1>
enable_if< is_convertible< Protocol1, Protocol >::value, basic_socket_acceptor >::type & operator=(
    basic_socket_acceptor< Protocol1, SocketAcceptorService1 > && other);

This assignment operator moves an acceptor from one object to another.

Parameters

other

The other basic_socket_acceptor object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_socket(io_service&) constructor.

The protocol type.

typedef Protocol protocol_type;
Requirements

Header: boost/asio/basic_socket_acceptor.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option for the receive buffer size of a socket.

typedef implementation_defined receive_buffer_size;

Implements the SOL_SOCKET/SO_RCVBUF socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_buffer_size option(8192);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_buffer_size option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/basic_socket_acceptor.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option for the receive low watermark.

typedef implementation_defined receive_low_watermark;

Implements the SOL_SOCKET/SO_RCVLOWAT socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_low_watermark option(1024);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_low_watermark option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/basic_socket_acceptor.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option to allow the socket to be bound to an address that is already in use.

typedef implementation_defined reuse_address;

Implements the SOL_SOCKET/SO_REUSEADDR socket option.

Examples

Setting the option:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::reuse_address option(true);
acceptor.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::reuse_address option;
acceptor.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_socket_acceptor.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option for the send buffer size of a socket.

typedef implementation_defined send_buffer_size;

Implements the SOL_SOCKET/SO_SNDBUF socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_buffer_size option(8192);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_buffer_size option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/basic_socket_acceptor.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option for the send low watermark.

typedef implementation_defined send_low_watermark;

Implements the SOL_SOCKET/SO_SNDLOWAT socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_low_watermark option(1024);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_low_watermark option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/basic_socket_acceptor.hpp

Convenience header: boost/asio.hpp

Inherited from basic_io_object.

(Deprecated: Use get_service().) The service associated with the I/O object.

service_type & service;
Remarks

Available only for services that do not support movability.

Inherited from basic_io_object.

The type of the service that will be used to provide I/O operations.

typedef SocketAcceptorService service_type;
Requirements

Header: boost/asio/basic_socket_acceptor.hpp

Convenience header: boost/asio.hpp

Set an option on the acceptor.

template<
    typename SettableSocketOption>
void set_option(
    const SettableSocketOption & option);
  » more...

template<
    typename SettableSocketOption>
boost::system::error_code set_option(
    const SettableSocketOption & option,
    boost::system::error_code & ec);
  » more...

Set an option on the acceptor.

template<
    typename SettableSocketOption>
void set_option(
    const SettableSocketOption & option);

This function is used to set an option on the acceptor.

Parameters

option

The new option value to be set on the acceptor.

Exceptions

boost::system::system_error

Thrown on failure.

Example

Setting the SOL_SOCKET/SO_REUSEADDR option:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::ip::tcp::acceptor::reuse_address option(true);
acceptor.set_option(option);

Set an option on the acceptor.

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 acceptor.

Parameters

option

The new option value to be set on the acceptor.

ec

Set to indicate what error occurred, if any.

Example

Setting the SOL_SOCKET/SO_REUSEADDR option:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::ip::tcp::acceptor::reuse_address option(true);
boost::system::error_code ec;
acceptor.set_option(option, ec);
if (ec)
{
  // An error occurred.
}

Inherited from socket_base.

Different ways a socket may be shutdown.

enum shutdown_type

Values

shutdown_receive

Shutdown the receive side of the socket.

shutdown_send

Shutdown the send side of the socket.

shutdown_both

Shutdown both send and receive on the socket.

Iostream interface for a socket.

template<
    typename Protocol,
    typename StreamSocketService = stream_socket_service<Protocol>,
    typename Time = boost::posix_time::ptime,
    typename TimeTraits = boost::asio::time_traits<Time>,
    typename TimerService = deadline_timer_service<Time, TimeTraits>>
class basic_socket_iostream
Types

Name

Description

duration_type

The duration type.

endpoint_type

The endpoint type.

time_type

The time type.

Member Functions

Name

Description

basic_socket_iostream

Construct a basic_socket_iostream without establishing a connection.

Establish a connection to an endpoint corresponding to a resolver query.

close

Close the connection.

connect

Establish a connection to an endpoint corresponding to a resolver query.

error

Get the last error associated with the stream.

expires_at

Get the stream's expiry time as an absolute time.

Set the stream's expiry time as an absolute time.

expires_from_now

Get the timer's expiry time relative to now.

Set the stream's expiry time relative to now.

rdbuf

Return a pointer to the underlying streambuf.

Requirements

Header: boost/asio/basic_socket_iostream.hpp

Convenience header: boost/asio.hpp

Construct a basic_socket_iostream without establishing a connection.

basic_socket_iostream();
  » more...

Establish a connection to an endpoint corresponding to a resolver query.

template<
    typename T1,
    ... ,
    typename TN>
explicit basic_socket_iostream(
    T1 t1,
    ... ,
    TN tn);
  » more...

Construct a basic_socket_iostream without establishing a connection.

basic_socket_iostream();

Establish a connection to an endpoint corresponding to a resolver query.

template<
    typename T1,
    ... ,
    typename TN>
basic_socket_iostream(
    T1 t1,
    ... ,
    TN tn);

This constructor automatically establishes a connection based on the supplied resolver query parameters. The arguments are used to construct a resolver query object.

Close the connection.

void close();

Establish a connection to an endpoint corresponding to a resolver query.

template<
    typename T1,
    ... ,
    typename TN>
void connect(
    T1 t1,
    ... ,
    TN tn);

This function automatically establishes a connection based on the supplied resolver query parameters. The arguments are used to construct a resolver query object.

The duration type.

typedef TimeTraits::duration_type duration_type;
Requirements

Header: boost/asio/basic_socket_iostream.hpp

Convenience header: boost/asio.hpp

The endpoint type.

typedef Protocol::endpoint endpoint_type;
Requirements

Header: boost/asio/basic_socket_iostream.hpp

Convenience header: boost/asio.hpp

Get the last error associated with the stream.

const boost::system::error_code & error() const;
Return Value

An error_code corresponding to the last error from the stream.

Example

To print the error associated with a failure to establish a connection:

tcp::iostream s("www.boost.org", "http");
if (!s)
{
  std::cout << "Error: " << s.error().message() << std::endl;
}

Get the stream's expiry time as an absolute time.

time_type expires_at() const;
  » more...

Set the stream's expiry time as an absolute time.

void expires_at(
    const time_type & expiry_time);
  » more...

Get the stream's expiry time as an absolute time.

time_type expires_at() const;
Return Value

An absolute time value representing the stream's expiry time.

Set the stream's expiry time as an absolute time.

void expires_at(
    const time_type & expiry_time);

This function sets the expiry time associated with the stream. Stream operations performed after this time (where the operations cannot be completed using the internal buffers) will fail with the error boost::asio::error::operation_aborted.

Parameters

expiry_time

The expiry time to be used for the stream.

Get the timer's expiry time relative to now.

duration_type expires_from_now() const;
  » more...

Set the stream's expiry time relative to now.

void expires_from_now(
    const duration_type & expiry_time);
  » more...

Get the timer's expiry time relative to now.

duration_type expires_from_now() const;
Return Value

A relative time value representing the stream's expiry time.

Set the stream's expiry time relative to now.

void expires_from_now(
    const duration_type & expiry_time);

This function sets the expiry time associated with the stream. Stream operations performed after this time (where the operations cannot be completed using the internal buffers) will fail with the error boost::asio::error::operation_aborted.

Parameters

expiry_time

The expiry time to be used for the timer.

Return a pointer to the underlying streambuf.

basic_socket_streambuf< Protocol, StreamSocketService, Time, TimeTraits, TimerService > * rdbuf() const;

The time type.

typedef TimeTraits::time_type time_type;
Requirements

Header: boost/asio/basic_socket_iostream.hpp

Convenience header: boost/asio.hpp

basic_socket_streambuf::assign
basic_socket_streambuf::async_connect
basic_socket_streambuf::at_mark
basic_socket_streambuf::available
basic_socket_streambuf::basic_socket_streambuf
basic_socket_streambuf::bind
basic_socket_streambuf::broadcast
basic_socket_streambuf::bytes_readable
basic_socket_streambuf::cancel
basic_socket_streambuf::close
basic_socket_streambuf::connect
basic_socket_streambuf::debug
basic_socket_streambuf::do_not_route
basic_socket_streambuf::duration_type
basic_socket_streambuf::enable_connection_aborted
basic_socket_streambuf::endpoint_type
basic_socket_streambuf::error
basic_socket_streambuf::expires_at
basic_socket_streambuf::expires_from_now
basic_socket_streambuf::get_implementation
basic_socket_streambuf::get_io_service
basic_socket_streambuf::get_option
basic_socket_streambuf::get_service
basic_socket_streambuf::implementation
basic_socket_streambuf::implementation_type
basic_socket_streambuf::io_control
basic_socket_streambuf::io_handler
basic_socket_streambuf::is_open
basic_socket_streambuf::keep_alive
basic_socket_streambuf::linger
basic_socket_streambuf::local_endpoint
basic_socket_streambuf::lowest_layer
basic_socket_streambuf::lowest_layer_type
basic_socket_streambuf::max_connections
basic_socket_streambuf::message_do_not_route
basic_socket_streambuf::message_end_of_record
basic_socket_streambuf::message_flags
basic_socket_streambuf::message_out_of_band
basic_socket_streambuf::message_peek
basic_socket_streambuf::native
basic_socket_streambuf::native_handle
basic_socket_streambuf::native_handle_type
basic_socket_streambuf::native_non_blocking
basic_socket_streambuf::native_type
basic_socket_streambuf::non_blocking
basic_socket_streambuf::non_blocking_io
basic_socket_streambuf::open
basic_socket_streambuf::overflow
basic_socket_streambuf::protocol_type
basic_socket_streambuf::puberror
basic_socket_streambuf::receive_buffer_size
basic_socket_streambuf::receive_low_watermark
basic_socket_streambuf::remote_endpoint
basic_socket_streambuf::reuse_address
basic_socket_streambuf::send_buffer_size
basic_socket_streambuf::send_low_watermark
basic_socket_streambuf::service
basic_socket_streambuf::service_type
basic_socket_streambuf::set_option
basic_socket_streambuf::setbuf
basic_socket_streambuf::shutdown
basic_socket_streambuf::shutdown_type
basic_socket_streambuf::sync
basic_socket_streambuf::time_type
basic_socket_streambuf::timer_handler
basic_socket_streambuf::underflow
basic_socket_streambuf::~basic_socket_streambuf

Iostream streambuf for a socket.

template<
    typename Protocol,
    typename StreamSocketService = stream_socket_service<Protocol>,
    typename Time = boost::posix_time::ptime,
    typename TimeTraits = boost::asio::time_traits<Time>,
    typename TimerService = deadline_timer_service<Time, TimeTraits>>
class basic_socket_streambuf :
  public basic_socket< Protocol, StreamSocketService >
Types

Name

Description

broadcast

Socket option to permit sending of broadcast messages.

bytes_readable

IO control command to get the amount of data that can be read without blocking.

debug

Socket option to enable socket-level debugging.

do_not_route

Socket option to prevent routing, use local interfaces only.

duration_type

The duration type.

enable_connection_aborted

Socket option to report aborted connections on accept.

endpoint_type

The endpoint type.

implementation_type

The underlying implementation type of I/O object.

keep_alive

Socket option to send keep-alives.

linger

Socket option to specify whether the socket lingers on close if unsent data is present.

lowest_layer_type

A basic_socket is always the lowest layer.

message_flags

Bitmask type for flags that can be passed to send and receive operations.

native_handle_type

The native representation of a socket.

native_type

(Deprecated: Use native_handle_type.) The native representation of a socket.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

protocol_type

The protocol type.

receive_buffer_size

Socket option for the receive buffer size of a socket.

receive_low_watermark

Socket option for the receive low watermark.

reuse_address

Socket option to allow the socket to be bound to an address that is already in use.

send_buffer_size

Socket option for the send buffer size of a socket.

send_low_watermark

Socket option for the send low watermark.

service_type

The type of the service that will be used to provide I/O operations.

shutdown_type

Different ways a socket may be shutdown.

time_type

The time type.

Member Functions

Name

Description

assign

Assign an existing native socket to the socket.

async_connect

Start an asynchronous connect.

at_mark

Determine whether the socket is at the out-of-band data mark.

available

Determine the number of bytes available for reading.

basic_socket_streambuf

Construct a basic_socket_streambuf without establishing a connection.

bind

Bind the socket to the given local endpoint.

cancel

Cancel all asynchronous operations associated with the socket.

close

Close the connection.

Close the socket.

connect

Establish a connection.

Connect the socket to the specified endpoint.

expires_at

Get the stream buffer's expiry time as an absolute time.

Set the stream buffer's expiry time as an absolute time.

expires_from_now

Get the stream buffer's expiry time relative to now.

Set the stream buffer's expiry time relative to now.

get_io_service

Get the io_service associated with the object.

get_option

Get an option from the socket.

io_control

Perform an IO control command on the socket.

is_open

Determine whether the socket is open.

local_endpoint

Get the local endpoint of the socket.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native socket representation.

native_handle

Get the native socket representation.

native_non_blocking

Gets the non-blocking mode of the native socket implementation.

Sets the non-blocking mode of the native socket implementation.

non_blocking

Gets the non-blocking mode of the socket.

Sets the non-blocking mode of the socket.

open

Open the socket using the specified protocol.

puberror

Get the last error associated with the stream buffer.

remote_endpoint

Get the remote endpoint of the socket.

set_option

Set an option on the socket.

shutdown

Disable sends or receives on the socket.

~basic_socket_streambuf

Destructor flushes buffered data.

Protected Member Functions

Name

Description

error

Get the last error associated with the stream buffer.

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

overflow

setbuf

sync

underflow

Data Members

Name

Description

max_connections

The maximum length of the queue of pending incoming connections.

message_do_not_route

Specify that the data should not be subject to routing.

message_end_of_record

Specifies that the data marks the end of a record.

message_out_of_band

Process out-of-band data.

message_peek

Peek at incoming data without removing it from the input queue.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

Friends

Name

Description

io_handler

timer_handler

Requirements

Header: boost/asio/basic_socket_streambuf.hpp

Convenience header: boost/asio.hpp

Assign an existing native socket to the socket.

void assign(
    const protocol_type & protocol,
    const native_handle_type & native_socket);
  » more...

boost::system::error_code assign(
    const protocol_type & protocol,
    const native_handle_type & native_socket,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Assign an existing native socket to the socket.

void assign(
    const protocol_type & protocol,
    const native_handle_type & native_socket);

Inherited from basic_socket.

Assign an existing native socket to the socket.

boost::system::error_code assign(
    const protocol_type & protocol,
    const native_handle_type & native_socket,
    boost::system::error_code & ec);

Inherited from basic_socket.

Start an asynchronous connect.

template<
    typename ConnectHandler>
void-or-deduced async_connect(
    const endpoint_type & peer_endpoint,
    ConnectHandler handler);

This function is used to asynchronously connect a socket to the specified remote endpoint. The function call always returns immediately.

The socket is automatically opened if it is not already open. If the connect fails, and the socket was automatically opened, the socket is not returned to the closed state.

Parameters

peer_endpoint

The remote endpoint to which the socket will be connected. Copies will be made of the endpoint object as required.

handler

The handler to be called when the connection operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error // Result of operation
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Example
void connect_handler(const boost::system::error_code& error)
{
  if (!error)
  {
    // Connect succeeded.
  }
}

...

boost::asio::ip::tcp::socket socket(io_service);
boost::asio::ip::tcp::endpoint endpoint(
    boost::asio::ip::address::from_string("1.2.3.4"), 12345);
socket.async_connect(endpoint, connect_handler);

Determine whether the socket is at the out-of-band data mark.

bool at_mark() const;
  » more...

bool at_mark(
    boost::system::error_code & ec) const;
  » more...

Inherited from basic_socket.

Determine whether the socket is at the out-of-band data mark.

bool at_mark() const;

This function is used to check whether the socket input is currently positioned at the out-of-band data mark.

Return Value

A bool indicating whether the socket is at the out-of-band data mark.

Exceptions

boost::system::system_error

Thrown on failure.

Inherited from basic_socket.

Determine whether the socket is at the out-of-band data mark.

bool at_mark(
    boost::system::error_code & ec) const;

This function is used to check whether the socket input is currently positioned at the out-of-band data mark.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

A bool indicating whether the socket is at the out-of-band data mark.

Determine the number of bytes available for reading.

std::size_t available() const;
  » more...

std::size_t available(
    boost::system::error_code & ec) const;
  » more...

Inherited from basic_socket.

Determine the number of bytes available for reading.

std::size_t available() const;

This function is used to determine the number of bytes that may be read without blocking.

Return Value

The number of bytes that may be read without blocking, or 0 if an error occurs.

Exceptions

boost::system::system_error

Thrown on failure.

Inherited from basic_socket.

Determine the number of bytes available for reading.

std::size_t available(
    boost::system::error_code & ec) const;

This function is used to determine the number of bytes that may be read without blocking.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes that may be read without blocking, or 0 if an error occurs.

Construct a basic_socket_streambuf without establishing a connection.

basic_socket_streambuf();

Bind the socket to the given local endpoint.

void bind(
    const endpoint_type & endpoint);
  » more...

boost::system::error_code bind(
    const endpoint_type & endpoint,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Bind the socket to the given local endpoint.

void bind(
    const endpoint_type & endpoint);

This function binds the socket to the specified endpoint on the local machine.

Parameters

endpoint

An endpoint on the local machine to which the socket will be bound.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::socket socket(io_service);
socket.open(boost::asio::ip::tcp::v4());
socket.bind(boost::asio::ip::tcp::endpoint(
      boost::asio::ip::tcp::v4(), 12345));

Inherited from basic_socket.

Bind the socket to the given local endpoint.

boost::system::error_code bind(
    const endpoint_type & endpoint,
    boost::system::error_code & ec);

This function binds the socket to the specified endpoint on the local machine.

Parameters

endpoint

An endpoint on the local machine to which the socket will be bound.

ec

Set to indicate what error occurred, if any.

Example
boost::asio::ip::tcp::socket socket(io_service);
socket.open(boost::asio::ip::tcp::v4());
boost::system::error_code ec;
socket.bind(boost::asio::ip::tcp::endpoint(
      boost::asio::ip::tcp::v4(), 12345), ec);
if (ec)
{
  // An error occurred.
}

Inherited from socket_base.

Socket option to permit sending of broadcast messages.

typedef implementation_defined broadcast;

Implements the SOL_SOCKET/SO_BROADCAST socket option.

Examples

Setting the option:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::broadcast option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::broadcast option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_socket_streambuf.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

IO control command to get the amount of data that can be read without blocking.

typedef implementation_defined bytes_readable;

Implements the FIONREAD IO control command.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::bytes_readable command(true);
socket.io_control(command);
std::size_t bytes_readable = command.get();
Requirements

Header: boost/asio/basic_socket_streambuf.hpp

Convenience header: boost/asio.hpp

Cancel all asynchronous operations associated with the socket.

void cancel();
  » more...

boost::system::error_code cancel(
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Cancel all asynchronous operations associated with the socket.

void cancel();

This function causes all outstanding asynchronous connect, send and receive operations to finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Calls to cancel() will always fail with boost::asio::error::operation_not_supported when run on Windows XP, Windows Server 2003, and earlier versions of Windows, unless BOOST_ASIO_ENABLE_CANCELIO is defined. However, the CancelIo function has two issues that should be considered before enabling its use:

  • It will only cancel asynchronous operations that were initiated in the current thread.
  • It can appear to complete without error, but the request to cancel the unfinished operations may be silently ignored by the operating system. Whether it works or not seems to depend on the drivers that are installed.

For portable cancellation, consider using one of the following alternatives:

  • Disable asio's I/O completion port backend by defining BOOST_ASIO_DISABLE_IOCP.
  • Use the close() function to simultaneously cancel the outstanding operations and close the socket.

When running on Windows Vista, Windows Server 2008, and later, the CancelIoEx function is always used. This function does not have the problems described above.

Inherited from basic_socket.

Cancel all asynchronous operations associated with the socket.

boost::system::error_code cancel(
    boost::system::error_code & ec);

This function causes all outstanding asynchronous connect, send and receive operations to finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error.

Parameters

ec

Set to indicate what error occurred, if any.

Remarks

Calls to cancel() will always fail with boost::asio::error::operation_not_supported when run on Windows XP, Windows Server 2003, and earlier versions of Windows, unless BOOST_ASIO_ENABLE_CANCELIO is defined. However, the CancelIo function has two issues that should be considered before enabling its use:

  • It will only cancel asynchronous operations that were initiated in the current thread.
  • It can appear to complete without error, but the request to cancel the unfinished operations may be silently ignored by the operating system. Whether it works or not seems to depend on the drivers that are installed.

For portable cancellation, consider using one of the following alternatives:

  • Disable asio's I/O completion port backend by defining BOOST_ASIO_DISABLE_IOCP.
  • Use the close() function to simultaneously cancel the outstanding operations and close the socket.

When running on Windows Vista, Windows Server 2008, and later, the CancelIoEx function is always used. This function does not have the problems described above.

Close the connection.

basic_socket_streambuf< Protocol, StreamSocketService, Time, TimeTraits, TimerService > * close();
  » more...

Close the socket.

boost::system::error_code close(
    boost::system::error_code & ec);
  » more...

Close the connection.

basic_socket_streambuf< Protocol, StreamSocketService, Time, TimeTraits, TimerService > * close();
Return Value

this if a connection was successfully established, a null pointer otherwise.

Inherited from basic_socket.

Close the socket.

boost::system::error_code close(
    boost::system::error_code & ec);

This function is used to close the socket. Any asynchronous send, receive or connect operations will be cancelled immediately, and will complete with the boost::asio::error::operation_aborted error.

Parameters

ec

Set to indicate what error occurred, if any. Note that, even if the function indicates an error, the underlying descriptor is closed.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::system::error_code ec;
socket.close(ec);
if (ec)
{
  // An error occurred.
}
Remarks

For portable behaviour with respect to graceful closure of a connected socket, call shutdown() before closing the socket.

Establish a connection.

basic_socket_streambuf< Protocol, StreamSocketService, Time, TimeTraits, TimerService > * connect(
    const endpoint_type & endpoint);
  » more...

template<
    typename T1,
    ... ,
    typename TN>
basic_socket_streambuf< Protocol, StreamSocketService > * connect(
    T1 t1,
    ... ,
    TN tn);
  » more...

Connect the socket to the specified endpoint.

boost::system::error_code connect(
    const endpoint_type & peer_endpoint,
    boost::system::error_code & ec);
  » more...

Establish a connection.

basic_socket_streambuf< Protocol, StreamSocketService, Time, TimeTraits, TimerService > * connect(
    const endpoint_type & endpoint);

This function establishes a connection to the specified endpoint.

Return Value

this if a connection was successfully established, a null pointer otherwise.

Establish a connection.

template<
    typename T1,
    ... ,
    typename TN>
basic_socket_streambuf< Protocol, StreamSocketService > * connect(
    T1 t1,
    ... ,
    TN tn);

This function automatically establishes a connection based on the supplied resolver query parameters. The arguments are used to construct a resolver query object.

Return Value

this if a connection was successfully established, a null pointer otherwise.

Inherited from basic_socket.

Connect the socket to the specified endpoint.

boost::system::error_code connect(
    const endpoint_type & peer_endpoint,
    boost::system::error_code & ec);

This function is used to connect a socket to the specified remote endpoint. The function call will block until the connection is successfully made or an error occurs.

The socket is automatically opened if it is not already open. If the connect fails, and the socket was automatically opened, the socket is not returned to the closed state.

Parameters

peer_endpoint

The remote endpoint to which the socket will be connected.

ec

Set to indicate what error occurred, if any.

Example
boost::asio::ip::tcp::socket socket(io_service);
boost::asio::ip::tcp::endpoint endpoint(
    boost::asio::ip::address::from_string("1.2.3.4"), 12345);
boost::system::error_code ec;
socket.connect(endpoint, ec);
if (ec)
{
  // An error occurred.
}

Inherited from socket_base.

Socket option to enable socket-level debugging.

typedef implementation_defined debug;

Implements the SOL_SOCKET/SO_DEBUG socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::debug option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::debug option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_socket_streambuf.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option to prevent routing, use local interfaces only.

typedef implementation_defined do_not_route;

Implements the SOL_SOCKET/SO_DONTROUTE socket option.

Examples

Setting the option:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::do_not_route option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::do_not_route option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_socket_streambuf.hpp

Convenience header: boost/asio.hpp

The duration type.

typedef TimeTraits::duration_type duration_type;
Requirements

Header: boost/asio/basic_socket_streambuf.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option to report aborted connections on accept.

typedef implementation_defined enable_connection_aborted;

Implements a custom socket option that determines whether or not an accept operation is permitted to fail with boost::asio::error::connection_aborted. By default the option is false.

Examples

Setting the option:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::enable_connection_aborted option(true);
acceptor.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::enable_connection_aborted option;
acceptor.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_socket_streambuf.hpp

Convenience header: boost/asio.hpp

The endpoint type.

typedef Protocol::endpoint endpoint_type;
Requirements

Header: boost/asio/basic_socket_streambuf.hpp

Convenience header: boost/asio.hpp

Get the last error associated with the stream buffer.

virtual const boost::system::error_code & error() const;
Return Value

An error_code corresponding to the last error from the stream buffer.

Get the stream buffer's expiry time as an absolute time.

time_type expires_at() const;
  » more...

Set the stream buffer's expiry time as an absolute time.

void expires_at(
    const time_type & expiry_time);
  » more...

Get the stream buffer's expiry time as an absolute time.

time_type expires_at() const;
Return Value

An absolute time value representing the stream buffer's expiry time.

Set the stream buffer's expiry time as an absolute time.

void expires_at(
    const time_type & expiry_time);

This function sets the expiry time associated with the stream. Stream operations performed after this time (where the operations cannot be completed using the internal buffers) will fail with the error boost::asio::error::operation_aborted.

Parameters

expiry_time

The expiry time to be used for the stream.

Get the stream buffer's expiry time relative to now.

duration_type expires_from_now() const;
  » more...

Set the stream buffer's expiry time relative to now.

void expires_from_now(
    const duration_type & expiry_time);
  » more...

Get the stream buffer's expiry time relative to now.

duration_type expires_from_now() const;
Return Value

A relative time value representing the stream buffer's expiry time.

Set the stream buffer's expiry time relative to now.

void expires_from_now(
    const duration_type & expiry_time);

This function sets the expiry time associated with the stream. Stream operations performed after this time (where the operations cannot be completed using the internal buffers) will fail with the error boost::asio::error::operation_aborted.

Parameters

expiry_time

The expiry time to be used for the timer.

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();
  » more...

const implementation_type & get_implementation() const;
  » more...

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

const implementation_type & get_implementation() const;

Inherited from basic_io_object.

Get the io_service associated with the object.

boost::asio::io_service & get_io_service();

This function may be used to obtain the io_service object that the I/O object uses to dispatch handlers for asynchronous operations.

Return Value

A reference to the io_service object that the I/O object will use to dispatch handlers. Ownership is not transferred to the caller.

Get an option from the socket.

void get_option(
    GettableSocketOption & option) const;
  » more...

boost::system::error_code get_option(
    GettableSocketOption & option,
    boost::system::error_code & ec) const;
  » more...

Inherited from basic_socket.

Get an option from the socket.

template<
    typename GettableSocketOption>
void get_option(
    GettableSocketOption & option) const;

This function is used to get the current value of an option on the socket.

Parameters

option

The option value to be obtained from the socket.

Exceptions

boost::system::system_error

Thrown on failure.

Example

Getting the value of the SOL_SOCKET/SO_KEEPALIVE option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::socket::keep_alive option;
socket.get_option(option);
bool is_set = option.value();

Inherited from basic_socket.

Get an option from the socket.

template<
    typename GettableSocketOption>
boost::system::error_code get_option(
    GettableSocketOption & option,
    boost::system::error_code & ec) const;

This function is used to get the current value of an option on the socket.

Parameters

option

The option value to be obtained from the socket.

ec

Set to indicate what error occurred, if any.

Example

Getting the value of the SOL_SOCKET/SO_KEEPALIVE option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::socket::keep_alive option;
boost::system::error_code ec;
socket.get_option(option, ec);
if (ec)
{
  // An error occurred.
}
bool is_set = option.value();

Get the service associated with the I/O object.

service_type & get_service();
  » more...

const service_type & get_service() const;
  » more...

Inherited from basic_io_object.

Get the service associated with the I/O object.

service_type & get_service();

Inherited from basic_io_object.

Get the service associated with the I/O object.

const service_type & get_service() const;

Inherited from basic_io_object.

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

implementation_type implementation;

Inherited from basic_io_object.

The underlying implementation type of I/O object.

typedef service_type::implementation_type implementation_type;
Requirements

Header: boost/asio/basic_socket_streambuf.hpp

Convenience header: boost/asio.hpp

Perform an IO control command on the socket.

void io_control(
    IoControlCommand & command);
  » more...

boost::system::error_code io_control(
    IoControlCommand & command,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Perform an IO control command on the socket.

template<
    typename IoControlCommand>
void io_control(
    IoControlCommand & command);

This function is used to execute an IO control command on the socket.

Parameters

command

The IO control command to be performed on the socket.

Exceptions

boost::system::system_error

Thrown on failure.

Example

Getting the number of bytes ready to read:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::socket::bytes_readable command;
socket.io_control(command);
std::size_t bytes_readable = command.get();

Inherited from basic_socket.

Perform an IO control command on the socket.

template<
    typename IoControlCommand>
boost::system::error_code io_control(
    IoControlCommand & command,
    boost::system::error_code & ec);

This function is used to execute an IO control command on the socket.

Parameters

command

The IO control command to be performed on the socket.

ec

Set to indicate what error occurred, if any.

Example

Getting the number of bytes ready to read:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::socket::bytes_readable command;
boost::system::error_code ec;
socket.io_control(command, ec);
if (ec)
{
  // An error occurred.
}
std::size_t bytes_readable = command.get();

friend struct io_handler();
Requirements

Header: boost/asio/basic_socket_streambuf.hpp

Convenience header: boost/asio.hpp

Inherited from basic_socket.

Determine whether the socket is open.

bool is_open() const;

Inherited from socket_base.

Socket option to send keep-alives.

typedef implementation_defined keep_alive;

Implements the SOL_SOCKET/SO_KEEPALIVE socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::keep_alive option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::keep_alive option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_socket_streambuf.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

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.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::linger option(true, 30);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::linger option;
socket.get_option(option);
bool is_set = option.enabled();
unsigned short timeout = option.timeout();
Requirements

Header: boost/asio/basic_socket_streambuf.hpp

Convenience header: boost/asio.hpp

Get the local endpoint of the socket.

endpoint_type local_endpoint() const;
  » more...

endpoint_type local_endpoint(
    boost::system::error_code & ec) const;
  » more...

Inherited from basic_socket.

Get the local endpoint of the socket.

endpoint_type local_endpoint() const;

This function is used to obtain the locally bound endpoint of the socket.

Return Value

An object that represents the local endpoint of the socket.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::endpoint endpoint = socket.local_endpoint();

Inherited from basic_socket.

Get the local endpoint of the socket.

endpoint_type local_endpoint(
    boost::system::error_code & ec) const;

This function is used to obtain the locally bound endpoint of the socket.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

An object that represents the local endpoint of the socket. Returns a default-constructed endpoint object if an error occurred.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::system::error_code ec;
boost::asio::ip::tcp::endpoint endpoint = socket.local_endpoint(ec);
if (ec)
{
  // An error occurred.
}

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();
  » more...

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;
  » more...

Inherited from basic_socket.

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();

This function returns a reference to the lowest layer in a stack of layers. Since a basic_socket cannot contain any further layers, it simply returns a reference to itself.

Return Value

A reference to the lowest layer in the stack of layers. Ownership is not transferred to the caller.

Inherited from basic_socket.

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;

This function returns a const reference to the lowest layer in a stack of layers. Since a basic_socket cannot contain any further layers, it simply returns a reference to itself.

Return Value

A const reference to the lowest layer in the stack of layers. Ownership is not transferred to the caller.

Inherited from basic_socket.

A basic_socket is always the lowest layer.

typedef basic_socket< Protocol, StreamSocketService > lowest_layer_type;
Types

Name

Description

broadcast

Socket option to permit sending of broadcast messages.

bytes_readable

IO control command to get the amount of data that can be read without blocking.

debug

Socket option to enable socket-level debugging.

do_not_route

Socket option to prevent routing, use local interfaces only.

enable_connection_aborted

Socket option to report aborted connections on accept.

endpoint_type

The endpoint type.

implementation_type

The underlying implementation type of I/O object.

keep_alive

Socket option to send keep-alives.

linger

Socket option to specify whether the socket lingers on close if unsent data is present.

lowest_layer_type

A basic_socket is always the lowest layer.

message_flags

Bitmask type for flags that can be passed to send and receive operations.

native_handle_type

The native representation of a socket.

native_type

(Deprecated: Use native_handle_type.) The native representation of a socket.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

protocol_type

The protocol type.

receive_buffer_size

Socket option for the receive buffer size of a socket.

receive_low_watermark

Socket option for the receive low watermark.

reuse_address

Socket option to allow the socket to be bound to an address that is already in use.

send_buffer_size

Socket option for the send buffer size of a socket.

send_low_watermark

Socket option for the send low watermark.

service_type

The type of the service that will be used to provide I/O operations.

shutdown_type

Different ways a socket may be shutdown.

Member Functions

Name

Description

assign

Assign an existing native socket to the socket.

async_connect

Start an asynchronous connect.

at_mark

Determine whether the socket is at the out-of-band data mark.

available

Determine the number of bytes available for reading.

basic_socket

Construct a basic_socket without opening it.

Construct and open a basic_socket.

Construct a basic_socket, opening it and binding it to the given local endpoint.

Construct a basic_socket on an existing native socket.

Move-construct a basic_socket from another.

Move-construct a basic_socket from a socket of another protocol type.

bind

Bind the socket to the given local endpoint.

cancel

Cancel all asynchronous operations associated with the socket.

close

Close the socket.

connect

Connect the socket to the specified endpoint.

get_io_service

Get the io_service associated with the object.

get_option

Get an option from the socket.

io_control

Perform an IO control command on the socket.

is_open

Determine whether the socket is open.

local_endpoint

Get the local endpoint of the socket.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native socket representation.

native_handle

Get the native socket representation.

native_non_blocking

Gets the non-blocking mode of the native socket implementation.

Sets the non-blocking mode of the native socket implementation.

non_blocking

Gets the non-blocking mode of the socket.

Sets the non-blocking mode of the socket.

open

Open the socket using the specified protocol.

operator=

Move-assign a basic_socket from another.

Move-assign a basic_socket from a socket of another protocol type.

remote_endpoint

Get the remote endpoint of the socket.

set_option

Set an option on the socket.

shutdown

Disable sends or receives on the socket.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

~basic_socket

Protected destructor to prevent deletion through this type.

Data Members

Name

Description

max_connections

The maximum length of the queue of pending incoming connections.

message_do_not_route

Specify that the data should not be subject to routing.

message_end_of_record

Specifies that the data marks the end of a record.

message_out_of_band

Process out-of-band data.

message_peek

Peek at incoming data without removing it from the input queue.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_socket class template provides functionality that is common to both stream-oriented and datagram-oriented sockets.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/basic_socket_streambuf.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

The maximum length of the queue of pending incoming connections.

static const int max_connections = implementation_defined;

Inherited from socket_base.

Specify that the data should not be subject to routing.

static const int message_do_not_route = implementation_defined;

Inherited from socket_base.

Specifies that the data marks the end of a record.

static const int message_end_of_record = implementation_defined;

Inherited from socket_base.

Bitmask type for flags that can be passed to send and receive operations.

typedef int message_flags;
Requirements

Header: boost/asio/basic_socket_streambuf.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Process out-of-band data.

static const int message_out_of_band = implementation_defined;

Inherited from socket_base.

Peek at incoming data without removing it from the input queue.

static const int message_peek = implementation_defined;

Inherited from basic_socket.

(Deprecated: Use native_handle().) Get the native socket representation.

native_type native();

This function may be used to obtain the underlying representation of the socket. This is intended to allow access to native socket functionality that is not otherwise provided.

Inherited from basic_socket.

Get the native socket representation.

native_handle_type native_handle();

This function may be used to obtain the underlying representation of the socket. This is intended to allow access to native socket functionality that is not otherwise provided.

Inherited from basic_socket.

The native representation of a socket.

typedef StreamSocketService::native_handle_type native_handle_type;
Requirements

Header: boost/asio/basic_socket_streambuf.hpp

Convenience header: boost/asio.hpp

Gets the non-blocking mode of the native socket implementation.

bool native_non_blocking() const;
  » more...

Sets the non-blocking mode of the native socket implementation.

void native_non_blocking(
    bool mode);
  » more...

boost::system::error_code native_non_blocking(
    bool mode,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Gets the non-blocking mode of the native socket implementation.

bool native_non_blocking() const;

This function is used to retrieve the non-blocking mode of the underlying native socket. This mode has no effect on the behaviour of the socket object's synchronous operations.

Return Value

true if the underlying socket is in non-blocking mode and direct system calls may fail with boost::asio::error::would_block (or the equivalent system error).

Remarks

The current non-blocking mode is cached by the socket object. Consequently, the return value may be incorrect if the non-blocking mode was set directly on the native socket.

Example

This function is intended to allow the encapsulation of arbitrary non-blocking system calls as asynchronous operations, in a way that is transparent to the user of the socket object. The following example illustrates how Linux's sendfile system call might be encapsulated:

template <typename Handler>
struct sendfile_op
{
  tcp::socket& sock_;
  int fd_;
  Handler handler_;
  off_t offset_;
  std::size_t total_bytes_transferred_;

  // Function call operator meeting WriteHandler requirements.
  // Used as the handler for the async_write_some operation.
  void operator()(boost::system::error_code ec, std::size_t)
  {
    // Put the underlying socket into non-blocking mode.
    if (!ec)
      if (!sock_.native_non_blocking())
        sock_.native_non_blocking(true, ec);

    if (!ec)
    {
      for (;;)
      {
        // Try the system call.
        errno = 0;
        int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536);
        ec = boost::system::error_code(n < 0 ? errno : 0,
            boost::asio::error::get_system_category());
        total_bytes_transferred_ += ec ? 0 : n;

        // Retry operation immediately if interrupted by signal.
        if (ec == boost::asio::error::interrupted)
          continue;

        // Check if we need to run the operation again.
        if (ec == boost::asio::error::would_block
            || ec == boost::asio::error::try_again)
        {
          // We have to wait for the socket to become ready again.
          sock_.async_write_some(boost::asio::null_buffers(), *this);
          return;
        }

        if (ec || n == 0)
        {
          // An error occurred, or we have reached the end of the file.
          // Either way we must exit the loop so we can call the handler.
          break;
        }

        // Loop around to try calling sendfile again.
      }
    }

    // Pass result back to user's handler.
    handler_(ec, total_bytes_transferred_);
  }
};

template <typename Handler>
void async_sendfile(tcp::socket& sock, int fd, Handler h)
{
  sendfile_op<Handler> op = { sock, fd, h, 0, 0 };
  sock.async_write_some(boost::asio::null_buffers(), op);
}

Inherited from basic_socket.

Sets the non-blocking mode of the native socket implementation.

void native_non_blocking(
    bool mode);

This function is used to modify the non-blocking mode of the underlying native socket. It has no effect on the behaviour of the socket object's synchronous operations.

Parameters

mode

If true, the underlying socket is put into non-blocking mode and direct system calls may fail with boost::asio::error::would_block (or the equivalent system error).

Exceptions

boost::system::system_error

Thrown on failure. If the mode is false, but the current value of non_blocking() is true, this function fails with boost::asio::error::invalid_argument, as the combination does not make sense.

Example

This function is intended to allow the encapsulation of arbitrary non-blocking system calls as asynchronous operations, in a way that is transparent to the user of the socket object. The following example illustrates how Linux's sendfile system call might be encapsulated:

template <typename Handler>
struct sendfile_op
{
  tcp::socket& sock_;
  int fd_;
  Handler handler_;
  off_t offset_;
  std::size_t total_bytes_transferred_;

  // Function call operator meeting WriteHandler requirements.
  // Used as the handler for the async_write_some operation.
  void operator()(boost::system::error_code ec, std::size_t)
  {
    // Put the underlying socket into non-blocking mode.
    if (!ec)
      if (!sock_.native_non_blocking())
        sock_.native_non_blocking(true, ec);

    if (!ec)
    {
      for (;;)
      {
        // Try the system call.
        errno = 0;
        int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536);
        ec = boost::system::error_code(n < 0 ? errno : 0,
            boost::asio::error::get_system_category());
        total_bytes_transferred_ += ec ? 0 : n;

        // Retry operation immediately if interrupted by signal.
        if (ec == boost::asio::error::interrupted)
          continue;

        // Check if we need to run the operation again.
        if (ec == boost::asio::error::would_block
            || ec == boost::asio::error::try_again)
        {
          // We have to wait for the socket to become ready again.
          sock_.async_write_some(boost::asio::null_buffers(), *this);
          return;
        }

        if (ec || n == 0)
        {
          // An error occurred, or we have reached the end of the file.
          // Either way we must exit the loop so we can call the handler.
          break;
        }

        // Loop around to try calling sendfile again.
      }
    }

    // Pass result back to user's handler.
    handler_(ec, total_bytes_transferred_);
  }
};

template <typename Handler>
void async_sendfile(tcp::socket& sock, int fd, Handler h)
{
  sendfile_op<Handler> op = { sock, fd, h, 0, 0 };
  sock.async_write_some(boost::asio::null_buffers(), op);
}

Inherited from basic_socket.

Sets the non-blocking mode of the native socket implementation.

boost::system::error_code native_non_blocking(
    bool mode,
    boost::system::error_code & ec);

This function is used to modify the non-blocking mode of the underlying native socket. It has no effect on the behaviour of the socket object's synchronous operations.

Parameters

mode

If true, the underlying socket is put into non-blocking mode and direct system calls may fail with boost::asio::error::would_block (or the equivalent system error).

ec

Set to indicate what error occurred, if any. If the mode is false, but the current value of non_blocking() is true, this function fails with boost::asio::error::invalid_argument, as the combination does not make sense.

Example

This function is intended to allow the encapsulation of arbitrary non-blocking system calls as asynchronous operations, in a way that is transparent to the user of the socket object. The following example illustrates how Linux's sendfile system call might be encapsulated:

template <typename Handler>
struct sendfile_op
{
  tcp::socket& sock_;
  int fd_;
  Handler handler_;
  off_t offset_;
  std::size_t total_bytes_transferred_;

  // Function call operator meeting WriteHandler requirements.
  // Used as the handler for the async_write_some operation.
  void operator()(boost::system::error_code ec, std::size_t)
  {
    // Put the underlying socket into non-blocking mode.
    if (!ec)
      if (!sock_.native_non_blocking())
        sock_.native_non_blocking(true, ec);

    if (!ec)
    {
      for (;;)
      {
        // Try the system call.
        errno = 0;
        int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536);
        ec = boost::system::error_code(n < 0 ? errno : 0,
            boost::asio::error::get_system_category());
        total_bytes_transferred_ += ec ? 0 : n;

        // Retry operation immediately if interrupted by signal.
        if (ec == boost::asio::error::interrupted)
          continue;

        // Check if we need to run the operation again.
        if (ec == boost::asio::error::would_block
            || ec == boost::asio::error::try_again)
        {
          // We have to wait for the socket to become ready again.
          sock_.async_write_some(boost::asio::null_buffers(), *this);
          return;
        }

        if (ec || n == 0)
        {
          // An error occurred, or we have reached the end of the file.
          // Either way we must exit the loop so we can call the handler.
          break;
        }

        // Loop around to try calling sendfile again.
      }
    }

    // Pass result back to user's handler.
    handler_(ec, total_bytes_transferred_);
  }
};

template <typename Handler>
void async_sendfile(tcp::socket& sock, int fd, Handler h)
{
  sendfile_op<Handler> op = { sock, fd, h, 0, 0 };
  sock.async_write_some(boost::asio::null_buffers(), op);
}

Inherited from basic_socket.

(Deprecated: Use native_handle_type.) The native representation of a socket.

typedef StreamSocketService::native_handle_type native_type;
Requirements

Header: boost/asio/basic_socket_streambuf.hpp

Convenience header: boost/asio.hpp

Gets the non-blocking mode of the socket.

bool non_blocking() const;
  » more...

Sets the non-blocking mode of the socket.

void non_blocking(
    bool mode);
  » more...

boost::system::error_code non_blocking(
    bool mode,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Gets the non-blocking mode of the socket.

bool non_blocking() const;
Return Value

true if the socket's synchronous operations will fail with boost::asio::error::would_block if they are unable to perform the requested operation immediately. If false, synchronous operations will block until complete.

Remarks

The non-blocking mode has no effect on the behaviour of asynchronous operations. Asynchronous operations will never fail with the error boost::asio::error::would_block.

Inherited from basic_socket.

Sets the non-blocking mode of the socket.

void non_blocking(
    bool mode);
Parameters

mode

If true, the socket's synchronous operations will fail with boost::asio::error::would_block if they are unable to perform the requested operation immediately. If false, synchronous operations will block until complete.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

The non-blocking mode has no effect on the behaviour of asynchronous operations. Asynchronous operations will never fail with the error boost::asio::error::would_block.

Inherited from basic_socket.

Sets the non-blocking mode of the socket.

boost::system::error_code non_blocking(
    bool mode,
    boost::system::error_code & ec);
Parameters

mode

If true, the socket's synchronous operations will fail with boost::asio::error::would_block if they are unable to perform the requested operation immediately. If false, synchronous operations will block until complete.

ec

Set to indicate what error occurred, if any.

Remarks

The non-blocking mode has no effect on the behaviour of asynchronous operations. Asynchronous operations will never fail with the error boost::asio::error::would_block.

Inherited from socket_base.

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

typedef implementation_defined non_blocking_io;

Implements the FIONBIO IO control command.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::non_blocking_io command(true);
socket.io_control(command);
Requirements

Header: boost/asio/basic_socket_streambuf.hpp

Convenience header: boost/asio.hpp

Open the socket using the specified protocol.

void open(
    const protocol_type & protocol = protocol_type());
  » more...

boost::system::error_code open(
    const protocol_type & protocol,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Open the socket using the specified protocol.

void open(
    const protocol_type & protocol = protocol_type());

This function opens the socket so that it will use the specified protocol.

Parameters

protocol

An object specifying protocol parameters to be used.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::socket socket(io_service);
socket.open(boost::asio::ip::tcp::v4());

Inherited from basic_socket.

Open the socket using the specified protocol.

boost::system::error_code open(
    const protocol_type & protocol,
    boost::system::error_code & ec);

This function opens the socket so that it will use the specified protocol.

Parameters

protocol

An object specifying which protocol is to be used.

ec

Set to indicate what error occurred, if any.

Example
boost::asio::ip::tcp::socket socket(io_service);
boost::system::error_code ec;
socket.open(boost::asio::ip::tcp::v4(), ec);
if (ec)
{
  // An error occurred.
}

int_type overflow(
    int_type c);

Inherited from basic_socket.

The protocol type.

typedef Protocol protocol_type;
Requirements

Header: boost/asio/basic_socket_streambuf.hpp

Convenience header: boost/asio.hpp

Get the last error associated with the stream buffer.

const boost::system::error_code & puberror() const;
Return Value

An error_code corresponding to the last error from the stream buffer.

Inherited from socket_base.

Socket option for the receive buffer size of a socket.

typedef implementation_defined receive_buffer_size;

Implements the SOL_SOCKET/SO_RCVBUF socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_buffer_size option(8192);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_buffer_size option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/basic_socket_streambuf.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option for the receive low watermark.

typedef implementation_defined receive_low_watermark;

Implements the SOL_SOCKET/SO_RCVLOWAT socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_low_watermark option(1024);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_low_watermark option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/basic_socket_streambuf.hpp

Convenience header: boost/asio.hpp

Get the remote endpoint of the socket.

endpoint_type remote_endpoint() const;
  » more...

endpoint_type remote_endpoint(
    boost::system::error_code & ec) const;
  » more...

Inherited from basic_socket.

Get the remote endpoint of the socket.

endpoint_type remote_endpoint() const;

This function is used to obtain the remote endpoint of the socket.

Return Value

An object that represents the remote endpoint of the socket.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::endpoint endpoint = socket.remote_endpoint();

Inherited from basic_socket.

Get the remote endpoint of the socket.

endpoint_type remote_endpoint(
    boost::system::error_code & ec) const;

This function is used to obtain the remote endpoint of the socket.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

An object that represents the remote endpoint of the socket. Returns a default-constructed endpoint object if an error occurred.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::system::error_code ec;
boost::asio::ip::tcp::endpoint endpoint = socket.remote_endpoint(ec);
if (ec)
{
  // An error occurred.
}

Inherited from socket_base.

Socket option to allow the socket to be bound to an address that is already in use.

typedef implementation_defined reuse_address;

Implements the SOL_SOCKET/SO_REUSEADDR socket option.

Examples

Setting the option:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::reuse_address option(true);
acceptor.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::reuse_address option;
acceptor.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_socket_streambuf.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option for the send buffer size of a socket.

typedef implementation_defined send_buffer_size;

Implements the SOL_SOCKET/SO_SNDBUF socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_buffer_size option(8192);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_buffer_size option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/basic_socket_streambuf.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option for the send low watermark.

typedef implementation_defined send_low_watermark;

Implements the SOL_SOCKET/SO_SNDLOWAT socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_low_watermark option(1024);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_low_watermark option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/basic_socket_streambuf.hpp

Convenience header: boost/asio.hpp

Inherited from basic_io_object.

(Deprecated: Use get_service().) The service associated with the I/O object.

service_type & service;
Remarks

Available only for services that do not support movability.

Inherited from basic_io_object.

The type of the service that will be used to provide I/O operations.

typedef StreamSocketService service_type;
Requirements

Header: boost/asio/basic_socket_streambuf.hpp

Convenience header: boost/asio.hpp

Set an option on the socket.

void set_option(
    const SettableSocketOption & option);
  » more...

boost::system::error_code set_option(
    const SettableSocketOption & option,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

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.

Parameters

option

The new option value to be set on the socket.

Exceptions

boost::system::system_error

Thrown on failure.

Example

Setting the IPPROTO_TCP/TCP_NODELAY option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::no_delay option(true);
socket.set_option(option);

Inherited from basic_socket.

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.

Parameters

option

The new option value to be set on the socket.

ec

Set to indicate what error occurred, if any.

Example

Setting the IPPROTO_TCP/TCP_NODELAY option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::no_delay option(true);
boost::system::error_code ec;
socket.set_option(option, ec);
if (ec)
{
  // An error occurred.
}

std::streambuf * setbuf(
    char_type * s,
    std::streamsize n);

Disable sends or receives on the socket.

void shutdown(
    shutdown_type what);
  » more...

boost::system::error_code shutdown(
    shutdown_type what,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Disable sends or receives on the socket.

void shutdown(
    shutdown_type what);

This function is used to disable send operations, receive operations, or both.

Parameters

what

Determines what types of operation will no longer be allowed.

Exceptions

boost::system::system_error

Thrown on failure.

Example

Shutting down the send side of the socket:

boost::asio::ip::tcp::socket socket(io_service);
...
socket.shutdown(boost::asio::ip::tcp::socket::shutdown_send);

Inherited from basic_socket.

Disable sends or receives on the socket.

boost::system::error_code shutdown(
    shutdown_type what,
    boost::system::error_code & ec);

This function is used to disable send operations, receive operations, or both.

Parameters

what

Determines what types of operation will no longer be allowed.

ec

Set to indicate what error occurred, if any.

Example

Shutting down the send side of the socket:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::system::error_code ec;
socket.shutdown(boost::asio::ip::tcp::socket::shutdown_send, ec);
if (ec)
{
  // An error occurred.
}

Inherited from socket_base.

Different ways a socket may be shutdown.

enum shutdown_type

Values

shutdown_receive

Shutdown the receive side of the socket.

shutdown_send

Shutdown the send side of the socket.

shutdown_both

Shutdown both send and receive on the socket.

The time type.

typedef TimeTraits::time_type time_type;
Requirements

Header: boost/asio/basic_socket_streambuf.hpp

Convenience header: boost/asio.hpp

friend struct timer_handler();
Requirements

Header: boost/asio/basic_socket_streambuf.hpp

Convenience header: boost/asio.hpp

int_type underflow();

Destructor flushes buffered data.

virtual ~basic_socket_streambuf();
basic_stream_socket::assign
basic_stream_socket::async_connect
basic_stream_socket::async_read_some
basic_stream_socket::async_receive
basic_stream_socket::async_send
basic_stream_socket::async_write_some
basic_stream_socket::at_mark
basic_stream_socket::available
basic_stream_socket::basic_stream_socket
basic_stream_socket::bind
basic_stream_socket::broadcast
basic_stream_socket::bytes_readable
basic_stream_socket::cancel
basic_stream_socket::close
basic_stream_socket::connect
basic_stream_socket::debug
basic_stream_socket::do_not_route
basic_stream_socket::enable_connection_aborted
basic_stream_socket::endpoint_type
basic_stream_socket::get_implementation
basic_stream_socket::get_io_service
basic_stream_socket::get_option
basic_stream_socket::get_service
basic_stream_socket::implementation
basic_stream_socket::implementation_type
basic_stream_socket::io_control
basic_stream_socket::is_open
basic_stream_socket::keep_alive
basic_stream_socket::linger
basic_stream_socket::local_endpoint
basic_stream_socket::lowest_layer
basic_stream_socket::lowest_layer_type
basic_stream_socket::max_connections
basic_stream_socket::message_do_not_route
basic_stream_socket::message_end_of_record
basic_stream_socket::message_flags
basic_stream_socket::message_out_of_band
basic_stream_socket::message_peek
basic_stream_socket::native
basic_stream_socket::native_handle
basic_stream_socket::native_handle_type
basic_stream_socket::native_non_blocking
basic_stream_socket::native_type
basic_stream_socket::non_blocking
basic_stream_socket::non_blocking_io
basic_stream_socket::open
basic_stream_socket::operator=
basic_stream_socket::protocol_type
basic_stream_socket::read_some
basic_stream_socket::receive
basic_stream_socket::receive_buffer_size
basic_stream_socket::receive_low_watermark
basic_stream_socket::remote_endpoint
basic_stream_socket::reuse_address
basic_stream_socket::send
basic_stream_socket::send_buffer_size
basic_stream_socket::send_low_watermark
basic_stream_socket::service
basic_stream_socket::service_type
basic_stream_socket::set_option
basic_stream_socket::shutdown
basic_stream_socket::shutdown_type
basic_stream_socket::write_some

Provides stream-oriented socket functionality.

template<
    typename Protocol,
    typename StreamSocketService = stream_socket_service<Protocol>>
class basic_stream_socket :
  public basic_socket< Protocol, StreamSocketService >
Types

Name

Description

broadcast

Socket option to permit sending of broadcast messages.

bytes_readable

IO control command to get the amount of data that can be read without blocking.

debug

Socket option to enable socket-level debugging.

do_not_route

Socket option to prevent routing, use local interfaces only.

enable_connection_aborted

Socket option to report aborted connections on accept.

endpoint_type

The endpoint type.

implementation_type

The underlying implementation type of I/O object.

keep_alive

Socket option to send keep-alives.

linger

Socket option to specify whether the socket lingers on close if unsent data is present.

lowest_layer_type

A basic_socket is always the lowest layer.

message_flags

Bitmask type for flags that can be passed to send and receive operations.

native_handle_type

The native representation of a socket.

native_type

(Deprecated: Use native_handle_type.) The native representation of a socket.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

protocol_type

The protocol type.

receive_buffer_size

Socket option for the receive buffer size of a socket.

receive_low_watermark

Socket option for the receive low watermark.

reuse_address

Socket option to allow the socket to be bound to an address that is already in use.

send_buffer_size

Socket option for the send buffer size of a socket.

send_low_watermark

Socket option for the send low watermark.

service_type

The type of the service that will be used to provide I/O operations.

shutdown_type

Different ways a socket may be shutdown.

Member Functions

Name

Description

assign

Assign an existing native socket to the socket.

async_connect

Start an asynchronous connect.

async_read_some

Start an asynchronous read.

async_receive

Start an asynchronous receive.

async_send

Start an asynchronous send.

async_write_some

Start an asynchronous write.

at_mark

Determine whether the socket is at the out-of-band data mark.

available

Determine the number of bytes available for reading.

basic_stream_socket

Construct a basic_stream_socket without opening it.

Construct and open a basic_stream_socket.

Construct a basic_stream_socket, opening it and binding it to the given local endpoint.

Construct a basic_stream_socket on an existing native socket.

Move-construct a basic_stream_socket from another.

Move-construct a basic_stream_socket from a socket of another protocol type.

bind

Bind the socket to the given local endpoint.

cancel

Cancel all asynchronous operations associated with the socket.

close

Close the socket.

connect

Connect the socket to the specified endpoint.

get_io_service

Get the io_service associated with the object.

get_option

Get an option from the socket.

io_control

Perform an IO control command on the socket.

is_open

Determine whether the socket is open.

local_endpoint

Get the local endpoint of the socket.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native socket representation.

native_handle

Get the native socket representation.

native_non_blocking

Gets the non-blocking mode of the native socket implementation.

Sets the non-blocking mode of the native socket implementation.

non_blocking

Gets the non-blocking mode of the socket.

Sets the non-blocking mode of the socket.

open

Open the socket using the specified protocol.

operator=

Move-assign a basic_stream_socket from another.

Move-assign a basic_stream_socket from a socket of another protocol type.

read_some

Read some data from the socket.

receive

Receive some data on the socket.

Receive some data on a connected socket.

remote_endpoint

Get the remote endpoint of the socket.

send

Send some data on the socket.

set_option

Set an option on the socket.

shutdown

Disable sends or receives on the socket.

write_some

Write some data to the socket.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Data Members

Name

Description

max_connections

The maximum length of the queue of pending incoming connections.

message_do_not_route

Specify that the data should not be subject to routing.

message_end_of_record

Specifies that the data marks the end of a record.

message_out_of_band

Process out-of-band data.

message_peek

Peek at incoming data without removing it from the input queue.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_stream_socket class template provides asynchronous and blocking stream-oriented socket functionality.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/basic_stream_socket.hpp

Convenience header: boost/asio.hpp

Assign an existing native socket to the socket.

void assign(
    const protocol_type & protocol,
    const native_handle_type & native_socket);
  » more...

boost::system::error_code assign(
    const protocol_type & protocol,
    const native_handle_type & native_socket,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Assign an existing native socket to the socket.

void assign(
    const protocol_type & protocol,
    const native_handle_type & native_socket);

Inherited from basic_socket.

Assign an existing native socket to the socket.

boost::system::error_code assign(
    const protocol_type & protocol,
    const native_handle_type & native_socket,
    boost::system::error_code & ec);

Inherited from basic_socket.

Start an asynchronous connect.

template<
    typename ConnectHandler>
void-or-deduced async_connect(
    const endpoint_type & peer_endpoint,
    ConnectHandler handler);

This function is used to asynchronously connect a socket to the specified remote endpoint. The function call always returns immediately.

The socket is automatically opened if it is not already open. If the connect fails, and the socket was automatically opened, the socket is not returned to the closed state.

Parameters

peer_endpoint

The remote endpoint to which the socket will be connected. Copies will be made of the endpoint object as required.

handler

The handler to be called when the connection operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error // Result of operation
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Example
void connect_handler(const boost::system::error_code& error)
{
  if (!error)
  {
    // Connect succeeded.
  }
}

...

boost::asio::ip::tcp::socket socket(io_service);
boost::asio::ip::tcp::endpoint endpoint(
    boost::asio::ip::address::from_string("1.2.3.4"), 12345);
socket.async_connect(endpoint, connect_handler);

Start an asynchronous read.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_read_some(
    const MutableBufferSequence & buffers,
    ReadHandler handler);

This function is used to asynchronously read data from the stream socket. The function call always returns immediately.

Parameters

buffers

One or more buffers into which the data will be read. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

handler

The handler to be called when the read operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes read.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

The read operation may not read all of the requested number of bytes. Consider using the async_read function if you need to ensure that the requested amount of data is read before the asynchronous operation completes.

Example

To read into a single data buffer use the buffer function as follows:

socket.async_read_some(boost::asio::buffer(data, size), handler);

See the buffer documentation for information on reading into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Start an asynchronous receive.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_receive(
    const MutableBufferSequence & buffers,
    ReadHandler handler);
  » more...

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_receive(
    const MutableBufferSequence & buffers,
    socket_base::message_flags flags,
    ReadHandler handler);
  » more...

Start an asynchronous receive.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_receive(
    const MutableBufferSequence & buffers,
    ReadHandler handler);

This function is used to asynchronously receive data from the stream socket. The function call always returns immediately.

Parameters

buffers

One or more buffers into which the data will be received. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

handler

The handler to be called when the receive operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes received.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

The receive operation may not receive all of the requested number of bytes. Consider using the async_read function if you need to ensure that the requested amount of data is received before the asynchronous operation completes.

Example

To receive into a single data buffer use the buffer function as follows:

socket.async_receive(boost::asio::buffer(data, size), handler);

See the buffer documentation for information on receiving into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Start an asynchronous receive.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_receive(
    const MutableBufferSequence & buffers,
    socket_base::message_flags flags,
    ReadHandler handler);

This function is used to asynchronously receive data from the stream socket. The function call always returns immediately.

Parameters

buffers

One or more buffers into which the data will be received. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

flags

Flags specifying how the receive call is to be made.

handler

The handler to be called when the receive operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes received.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

The receive operation may not receive all of the requested number of bytes. Consider using the async_read function if you need to ensure that the requested amount of data is received before the asynchronous operation completes.

Example

To receive into a single data buffer use the buffer function as follows:

socket.async_receive(boost::asio::buffer(data, size), 0, handler);

See the buffer documentation for information on receiving into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Start an asynchronous send.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_send(
    const ConstBufferSequence & buffers,
    WriteHandler handler);
  » more...

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_send(
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags,
    WriteHandler handler);
  » more...

Start an asynchronous send.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_send(
    const ConstBufferSequence & buffers,
    WriteHandler handler);

This function is used to asynchronously send data on the stream socket. The function call always returns immediately.

Parameters

buffers

One or more data buffers to be sent on the socket. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

handler

The handler to be called when the send operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes sent.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

The send operation may not transmit all of the data to the peer. Consider using the async_write function if you need to ensure that all data is written before the asynchronous operation completes.

Example

To send a single data buffer use the buffer function as follows:

socket.async_send(boost::asio::buffer(data, size), handler);

See the buffer documentation for information on sending multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Start an asynchronous send.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_send(
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags,
    WriteHandler handler);

This function is used to asynchronously send data on the stream socket. The function call always returns immediately.

Parameters

buffers

One or more data buffers to be sent on the socket. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

flags

Flags specifying how the send call is to be made.

handler

The handler to be called when the send operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes sent.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

The send operation may not transmit all of the data to the peer. Consider using the async_write function if you need to ensure that all data is written before the asynchronous operation completes.

Example

To send a single data buffer use the buffer function as follows:

socket.async_send(boost::asio::buffer(data, size), 0, handler);

See the buffer documentation for information on sending multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Start an asynchronous write.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_write_some(
    const ConstBufferSequence & buffers,
    WriteHandler handler);

This function is used to asynchronously write data to the stream socket. The function call always returns immediately.

Parameters

buffers

One or more data buffers to be written to the socket. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

handler

The handler to be called when the write operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes written.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

The write operation may not transmit all of the data to the peer. Consider using the async_write function if you need to ensure that all data is written before the asynchronous operation completes.

Example

To write a single data buffer use the buffer function as follows:

socket.async_write_some(boost::asio::buffer(data, size), handler);

See the buffer documentation for information on writing multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Determine whether the socket is at the out-of-band data mark.

bool at_mark() const;
  » more...

bool at_mark(
    boost::system::error_code & ec) const;
  » more...

Inherited from basic_socket.

Determine whether the socket is at the out-of-band data mark.

bool at_mark() const;

This function is used to check whether the socket input is currently positioned at the out-of-band data mark.

Return Value

A bool indicating whether the socket is at the out-of-band data mark.

Exceptions

boost::system::system_error

Thrown on failure.

Inherited from basic_socket.

Determine whether the socket is at the out-of-band data mark.

bool at_mark(
    boost::system::error_code & ec) const;

This function is used to check whether the socket input is currently positioned at the out-of-band data mark.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

A bool indicating whether the socket is at the out-of-band data mark.

Determine the number of bytes available for reading.

std::size_t available() const;
  » more...

std::size_t available(
    boost::system::error_code & ec) const;
  » more...

Inherited from basic_socket.

Determine the number of bytes available for reading.

std::size_t available() const;

This function is used to determine the number of bytes that may be read without blocking.

Return Value

The number of bytes that may be read without blocking, or 0 if an error occurs.

Exceptions

boost::system::system_error

Thrown on failure.

Inherited from basic_socket.

Determine the number of bytes available for reading.

std::size_t available(
    boost::system::error_code & ec) const;

This function is used to determine the number of bytes that may be read without blocking.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes that may be read without blocking, or 0 if an error occurs.

Construct a basic_stream_socket without opening it.

explicit basic_stream_socket(
    boost::asio::io_service & io_service);
  » more...

Construct and open a basic_stream_socket.

basic_stream_socket(
    boost::asio::io_service & io_service,
    const protocol_type & protocol);
  » more...

Construct a basic_stream_socket, opening it and binding it to the given local endpoint.

basic_stream_socket(
    boost::asio::io_service & io_service,
    const endpoint_type & endpoint);
  » more...

Construct a basic_stream_socket on an existing native socket.

basic_stream_socket(
    boost::asio::io_service & io_service,
    const protocol_type & protocol,
    const native_handle_type & native_socket);
  » more...

Move-construct a basic_stream_socket from another.

basic_stream_socket(
    basic_stream_socket && other);
  » more...

Move-construct a basic_stream_socket from a socket of another protocol type.

template<
    typename Protocol1,
    typename StreamSocketService1>
basic_stream_socket(
    basic_stream_socket< Protocol1, StreamSocketService1 > && other,
    typename enable_if< is_convertible< Protocol1, Protocol >::value >::type *  = 0);
  » more...

Construct a basic_stream_socket without opening it.

basic_stream_socket(
    boost::asio::io_service & io_service);

This constructor creates a stream socket without opening it. The socket needs to be opened and then connected or accepted before data can be sent or received on it.

Parameters

io_service

The io_service object that the stream socket will use to dispatch handlers for any asynchronous operations performed on the socket.

Construct and open a basic_stream_socket.

basic_stream_socket(
    boost::asio::io_service & io_service,
    const protocol_type & protocol);

This constructor creates and opens a stream socket. The socket needs to be connected or accepted before data can be sent or received on it.

Parameters

io_service

The io_service object that the stream socket will use to dispatch handlers for any asynchronous operations performed on the socket.

protocol

An object specifying protocol parameters to be used.

Exceptions

boost::system::system_error

Thrown on failure.

Construct a basic_stream_socket, opening it and binding it to the given local endpoint.

basic_stream_socket(
    boost::asio::io_service & io_service,
    const endpoint_type & endpoint);

This constructor creates a stream socket and automatically opens it bound to the specified endpoint on the local machine. The protocol used is the protocol associated with the given endpoint.

Parameters

io_service

The io_service object that the stream socket will use to dispatch handlers for any asynchronous operations performed on the socket.

endpoint

An endpoint on the local machine to which the stream socket will be bound.

Exceptions

boost::system::system_error

Thrown on failure.

Construct a basic_stream_socket on an existing native socket.

basic_stream_socket(
    boost::asio::io_service & io_service,
    const protocol_type & protocol,
    const native_handle_type & native_socket);

This constructor creates a stream socket object to hold an existing native socket.

Parameters

io_service

The io_service object that the stream socket will use to dispatch handlers for any asynchronous operations performed on the socket.

protocol

An object specifying protocol parameters to be used.

native_socket

The new underlying socket implementation.

Exceptions

boost::system::system_error

Thrown on failure.

Move-construct a basic_stream_socket from another.

basic_stream_socket(
    basic_stream_socket && other);

This constructor moves a stream socket from one object to another.

Parameters

other

The other basic_stream_socket object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_stream_socket(io_service&) constructor.

Move-construct a basic_stream_socket from a socket of another protocol type.

template<
    typename Protocol1,
    typename StreamSocketService1>
basic_stream_socket(
    basic_stream_socket< Protocol1, StreamSocketService1 > && other,
    typename enable_if< is_convertible< Protocol1, Protocol >::value >::type *  = 0);

This constructor moves a stream socket from one object to another.

Parameters

other

The other basic_stream_socket object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_stream_socket(io_service&) constructor.

Bind the socket to the given local endpoint.

void bind(
    const endpoint_type & endpoint);
  » more...

boost::system::error_code bind(
    const endpoint_type & endpoint,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Bind the socket to the given local endpoint.

void bind(
    const endpoint_type & endpoint);

This function binds the socket to the specified endpoint on the local machine.

Parameters

endpoint

An endpoint on the local machine to which the socket will be bound.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::socket socket(io_service);
socket.open(boost::asio::ip::tcp::v4());
socket.bind(boost::asio::ip::tcp::endpoint(
      boost::asio::ip::tcp::v4(), 12345));

Inherited from basic_socket.

Bind the socket to the given local endpoint.

boost::system::error_code bind(
    const endpoint_type & endpoint,
    boost::system::error_code & ec);

This function binds the socket to the specified endpoint on the local machine.

Parameters

endpoint

An endpoint on the local machine to which the socket will be bound.

ec

Set to indicate what error occurred, if any.

Example
boost::asio::ip::tcp::socket socket(io_service);
socket.open(boost::asio::ip::tcp::v4());
boost::system::error_code ec;
socket.bind(boost::asio::ip::tcp::endpoint(
      boost::asio::ip::tcp::v4(), 12345), ec);
if (ec)
{
  // An error occurred.
}

Inherited from socket_base.

Socket option to permit sending of broadcast messages.

typedef implementation_defined broadcast;

Implements the SOL_SOCKET/SO_BROADCAST socket option.

Examples

Setting the option:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::broadcast option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::broadcast option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_stream_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

IO control command to get the amount of data that can be read without blocking.

typedef implementation_defined bytes_readable;

Implements the FIONREAD IO control command.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::bytes_readable command(true);
socket.io_control(command);
std::size_t bytes_readable = command.get();
Requirements

Header: boost/asio/basic_stream_socket.hpp

Convenience header: boost/asio.hpp

Cancel all asynchronous operations associated with the socket.

void cancel();
  » more...

boost::system::error_code cancel(
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Cancel all asynchronous operations associated with the socket.

void cancel();

This function causes all outstanding asynchronous connect, send and receive operations to finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Calls to cancel() will always fail with boost::asio::error::operation_not_supported when run on Windows XP, Windows Server 2003, and earlier versions of Windows, unless BOOST_ASIO_ENABLE_CANCELIO is defined. However, the CancelIo function has two issues that should be considered before enabling its use:

  • It will only cancel asynchronous operations that were initiated in the current thread.
  • It can appear to complete without error, but the request to cancel the unfinished operations may be silently ignored by the operating system. Whether it works or not seems to depend on the drivers that are installed.

For portable cancellation, consider using one of the following alternatives:

  • Disable asio's I/O completion port backend by defining BOOST_ASIO_DISABLE_IOCP.
  • Use the close() function to simultaneously cancel the outstanding operations and close the socket.

When running on Windows Vista, Windows Server 2008, and later, the CancelIoEx function is always used. This function does not have the problems described above.

Inherited from basic_socket.

Cancel all asynchronous operations associated with the socket.

boost::system::error_code cancel(
    boost::system::error_code & ec);

This function causes all outstanding asynchronous connect, send and receive operations to finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error.

Parameters

ec

Set to indicate what error occurred, if any.

Remarks

Calls to cancel() will always fail with boost::asio::error::operation_not_supported when run on Windows XP, Windows Server 2003, and earlier versions of Windows, unless BOOST_ASIO_ENABLE_CANCELIO is defined. However, the CancelIo function has two issues that should be considered before enabling its use:

  • It will only cancel asynchronous operations that were initiated in the current thread.
  • It can appear to complete without error, but the request to cancel the unfinished operations may be silently ignored by the operating system. Whether it works or not seems to depend on the drivers that are installed.

For portable cancellation, consider using one of the following alternatives:

  • Disable asio's I/O completion port backend by defining BOOST_ASIO_DISABLE_IOCP.
  • Use the close() function to simultaneously cancel the outstanding operations and close the socket.

When running on Windows Vista, Windows Server 2008, and later, the CancelIoEx function is always used. This function does not have the problems described above.

Close the socket.

void close();
  » more...

boost::system::error_code close(
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Close the socket.

void close();

This function is used to close the socket. Any asynchronous send, receive or connect operations will be cancelled immediately, and will complete with the boost::asio::error::operation_aborted error.

Exceptions

boost::system::system_error

Thrown on failure. Note that, even if the function indicates an error, the underlying descriptor is closed.

Remarks

For portable behaviour with respect to graceful closure of a connected socket, call shutdown() before closing the socket.

Inherited from basic_socket.

Close the socket.

boost::system::error_code close(
    boost::system::error_code & ec);

This function is used to close the socket. Any asynchronous send, receive or connect operations will be cancelled immediately, and will complete with the boost::asio::error::operation_aborted error.

Parameters

ec

Set to indicate what error occurred, if any. Note that, even if the function indicates an error, the underlying descriptor is closed.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::system::error_code ec;
socket.close(ec);
if (ec)
{
  // An error occurred.
}
Remarks

For portable behaviour with respect to graceful closure of a connected socket, call shutdown() before closing the socket.

Connect the socket to the specified endpoint.

void connect(
    const endpoint_type & peer_endpoint);
  » more...

boost::system::error_code connect(
    const endpoint_type & peer_endpoint,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Connect the socket to the specified endpoint.

void connect(
    const endpoint_type & peer_endpoint);

This function is used to connect a socket to the specified remote endpoint. The function call will block until the connection is successfully made or an error occurs.

The socket is automatically opened if it is not already open. If the connect fails, and the socket was automatically opened, the socket is not returned to the closed state.

Parameters

peer_endpoint

The remote endpoint to which the socket will be connected.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::socket socket(io_service);
boost::asio::ip::tcp::endpoint endpoint(
    boost::asio::ip::address::from_string("1.2.3.4"), 12345);
socket.connect(endpoint);

Inherited from basic_socket.

Connect the socket to the specified endpoint.

boost::system::error_code connect(
    const endpoint_type & peer_endpoint,
    boost::system::error_code & ec);

This function is used to connect a socket to the specified remote endpoint. The function call will block until the connection is successfully made or an error occurs.

The socket is automatically opened if it is not already open. If the connect fails, and the socket was automatically opened, the socket is not returned to the closed state.

Parameters

peer_endpoint

The remote endpoint to which the socket will be connected.

ec

Set to indicate what error occurred, if any.

Example
boost::asio::ip::tcp::socket socket(io_service);
boost::asio::ip::tcp::endpoint endpoint(
    boost::asio::ip::address::from_string("1.2.3.4"), 12345);
boost::system::error_code ec;
socket.connect(endpoint, ec);
if (ec)
{
  // An error occurred.
}

Inherited from socket_base.

Socket option to enable socket-level debugging.

typedef implementation_defined debug;

Implements the SOL_SOCKET/SO_DEBUG socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::debug option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::debug option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_stream_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option to prevent routing, use local interfaces only.

typedef implementation_defined do_not_route;

Implements the SOL_SOCKET/SO_DONTROUTE socket option.

Examples

Setting the option:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::do_not_route option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::do_not_route option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_stream_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option to report aborted connections on accept.

typedef implementation_defined enable_connection_aborted;

Implements a custom socket option that determines whether or not an accept operation is permitted to fail with boost::asio::error::connection_aborted. By default the option is false.

Examples

Setting the option:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::enable_connection_aborted option(true);
acceptor.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::enable_connection_aborted option;
acceptor.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_stream_socket.hpp

Convenience header: boost/asio.hpp

The endpoint type.

typedef Protocol::endpoint endpoint_type;
Requirements

Header: boost/asio/basic_stream_socket.hpp

Convenience header: boost/asio.hpp

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();
  » more...

const implementation_type & get_implementation() const;
  » more...

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

const implementation_type & get_implementation() const;

Inherited from basic_io_object.

Get the io_service associated with the object.

boost::asio::io_service & get_io_service();

This function may be used to obtain the io_service object that the I/O object uses to dispatch handlers for asynchronous operations.

Return Value

A reference to the io_service object that the I/O object will use to dispatch handlers. Ownership is not transferred to the caller.

Get an option from the socket.

void get_option(
    GettableSocketOption & option) const;
  » more...

boost::system::error_code get_option(
    GettableSocketOption & option,
    boost::system::error_code & ec) const;
  » more...

Inherited from basic_socket.

Get an option from the socket.

template<
    typename GettableSocketOption>
void get_option(
    GettableSocketOption & option) const;

This function is used to get the current value of an option on the socket.

Parameters

option

The option value to be obtained from the socket.

Exceptions

boost::system::system_error

Thrown on failure.

Example

Getting the value of the SOL_SOCKET/SO_KEEPALIVE option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::socket::keep_alive option;
socket.get_option(option);
bool is_set = option.value();

Inherited from basic_socket.

Get an option from the socket.

template<
    typename GettableSocketOption>
boost::system::error_code get_option(
    GettableSocketOption & option,
    boost::system::error_code & ec) const;

This function is used to get the current value of an option on the socket.

Parameters

option

The option value to be obtained from the socket.

ec

Set to indicate what error occurred, if any.

Example

Getting the value of the SOL_SOCKET/SO_KEEPALIVE option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::socket::keep_alive option;
boost::system::error_code ec;
socket.get_option(option, ec);
if (ec)
{
  // An error occurred.
}
bool is_set = option.value();

Get the service associated with the I/O object.

service_type & get_service();
  » more...

const service_type & get_service() const;
  » more...

Inherited from basic_io_object.

Get the service associated with the I/O object.

service_type & get_service();

Inherited from basic_io_object.

Get the service associated with the I/O object.

const service_type & get_service() const;

Inherited from basic_io_object.

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

implementation_type implementation;

Inherited from basic_io_object.

The underlying implementation type of I/O object.

typedef service_type::implementation_type implementation_type;
Requirements

Header: boost/asio/basic_stream_socket.hpp

Convenience header: boost/asio.hpp

Perform an IO control command on the socket.

void io_control(
    IoControlCommand & command);
  » more...

boost::system::error_code io_control(
    IoControlCommand & command,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Perform an IO control command on the socket.

template<
    typename IoControlCommand>
void io_control(
    IoControlCommand & command);

This function is used to execute an IO control command on the socket.

Parameters

command

The IO control command to be performed on the socket.

Exceptions

boost::system::system_error

Thrown on failure.

Example

Getting the number of bytes ready to read:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::socket::bytes_readable command;
socket.io_control(command);
std::size_t bytes_readable = command.get();

Inherited from basic_socket.

Perform an IO control command on the socket.

template<
    typename IoControlCommand>
boost::system::error_code io_control(
    IoControlCommand & command,
    boost::system::error_code & ec);

This function is used to execute an IO control command on the socket.

Parameters

command

The IO control command to be performed on the socket.

ec

Set to indicate what error occurred, if any.

Example

Getting the number of bytes ready to read:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::socket::bytes_readable command;
boost::system::error_code ec;
socket.io_control(command, ec);
if (ec)
{
  // An error occurred.
}
std::size_t bytes_readable = command.get();

Inherited from basic_socket.

Determine whether the socket is open.

bool is_open() const;

Inherited from socket_base.

Socket option to send keep-alives.

typedef implementation_defined keep_alive;

Implements the SOL_SOCKET/SO_KEEPALIVE socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::keep_alive option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::keep_alive option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_stream_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

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.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::linger option(true, 30);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::linger option;
socket.get_option(option);
bool is_set = option.enabled();
unsigned short timeout = option.timeout();
Requirements

Header: boost/asio/basic_stream_socket.hpp

Convenience header: boost/asio.hpp

Get the local endpoint of the socket.

endpoint_type local_endpoint() const;
  » more...

endpoint_type local_endpoint(
    boost::system::error_code & ec) const;
  » more...

Inherited from basic_socket.

Get the local endpoint of the socket.

endpoint_type local_endpoint() const;

This function is used to obtain the locally bound endpoint of the socket.

Return Value

An object that represents the local endpoint of the socket.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::endpoint endpoint = socket.local_endpoint();

Inherited from basic_socket.

Get the local endpoint of the socket.

endpoint_type local_endpoint(
    boost::system::error_code & ec) const;

This function is used to obtain the locally bound endpoint of the socket.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

An object that represents the local endpoint of the socket. Returns a default-constructed endpoint object if an error occurred.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::system::error_code ec;
boost::asio::ip::tcp::endpoint endpoint = socket.local_endpoint(ec);
if (ec)
{
  // An error occurred.
}

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();
  » more...

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;
  » more...

Inherited from basic_socket.

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();

This function returns a reference to the lowest layer in a stack of layers. Since a basic_socket cannot contain any further layers, it simply returns a reference to itself.

Return Value

A reference to the lowest layer in the stack of layers. Ownership is not transferred to the caller.

Inherited from basic_socket.

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;

This function returns a const reference to the lowest layer in a stack of layers. Since a basic_socket cannot contain any further layers, it simply returns a reference to itself.

Return Value

A const reference to the lowest layer in the stack of layers. Ownership is not transferred to the caller.

Inherited from basic_socket.

A basic_socket is always the lowest layer.

typedef basic_socket< Protocol, StreamSocketService > lowest_layer_type;
Types

Name

Description

broadcast

Socket option to permit sending of broadcast messages.

bytes_readable

IO control command to get the amount of data that can be read without blocking.

debug

Socket option to enable socket-level debugging.

do_not_route

Socket option to prevent routing, use local interfaces only.

enable_connection_aborted

Socket option to report aborted connections on accept.

endpoint_type

The endpoint type.

implementation_type

The underlying implementation type of I/O object.

keep_alive

Socket option to send keep-alives.

linger

Socket option to specify whether the socket lingers on close if unsent data is present.

lowest_layer_type

A basic_socket is always the lowest layer.

message_flags

Bitmask type for flags that can be passed to send and receive operations.

native_handle_type

The native representation of a socket.

native_type

(Deprecated: Use native_handle_type.) The native representation of a socket.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

protocol_type

The protocol type.

receive_buffer_size

Socket option for the receive buffer size of a socket.

receive_low_watermark

Socket option for the receive low watermark.

reuse_address

Socket option to allow the socket to be bound to an address that is already in use.

send_buffer_size

Socket option for the send buffer size of a socket.

send_low_watermark

Socket option for the send low watermark.

service_type

The type of the service that will be used to provide I/O operations.

shutdown_type

Different ways a socket may be shutdown.

Member Functions

Name

Description

assign

Assign an existing native socket to the socket.

async_connect

Start an asynchronous connect.

at_mark

Determine whether the socket is at the out-of-band data mark.

available

Determine the number of bytes available for reading.

basic_socket

Construct a basic_socket without opening it.

Construct and open a basic_socket.

Construct a basic_socket, opening it and binding it to the given local endpoint.

Construct a basic_socket on an existing native socket.

Move-construct a basic_socket from another.

Move-construct a basic_socket from a socket of another protocol type.

bind

Bind the socket to the given local endpoint.

cancel

Cancel all asynchronous operations associated with the socket.

close

Close the socket.

connect

Connect the socket to the specified endpoint.

get_io_service

Get the io_service associated with the object.

get_option

Get an option from the socket.

io_control

Perform an IO control command on the socket.

is_open

Determine whether the socket is open.

local_endpoint

Get the local endpoint of the socket.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native socket representation.

native_handle

Get the native socket representation.

native_non_blocking

Gets the non-blocking mode of the native socket implementation.

Sets the non-blocking mode of the native socket implementation.

non_blocking

Gets the non-blocking mode of the socket.

Sets the non-blocking mode of the socket.

open

Open the socket using the specified protocol.

operator=

Move-assign a basic_socket from another.

Move-assign a basic_socket from a socket of another protocol type.

remote_endpoint

Get the remote endpoint of the socket.

set_option

Set an option on the socket.

shutdown

Disable sends or receives on the socket.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

~basic_socket

Protected destructor to prevent deletion through this type.

Data Members

Name

Description

max_connections

The maximum length of the queue of pending incoming connections.

message_do_not_route

Specify that the data should not be subject to routing.

message_end_of_record

Specifies that the data marks the end of a record.

message_out_of_band

Process out-of-band data.

message_peek

Peek at incoming data without removing it from the input queue.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_socket class template provides functionality that is common to both stream-oriented and datagram-oriented sockets.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/basic_stream_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

The maximum length of the queue of pending incoming connections.

static const int max_connections = implementation_defined;

Inherited from socket_base.

Specify that the data should not be subject to routing.

static const int message_do_not_route = implementation_defined;

Inherited from socket_base.

Specifies that the data marks the end of a record.

static const int message_end_of_record = implementation_defined;

Inherited from socket_base.

Bitmask type for flags that can be passed to send and receive operations.

typedef int message_flags;
Requirements

Header: boost/asio/basic_stream_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Process out-of-band data.

static const int message_out_of_band = implementation_defined;

Inherited from socket_base.

Peek at incoming data without removing it from the input queue.

static const int message_peek = implementation_defined;

Inherited from basic_socket.

(Deprecated: Use native_handle().) Get the native socket representation.

native_type native();

This function may be used to obtain the underlying representation of the socket. This is intended to allow access to native socket functionality that is not otherwise provided.

Inherited from basic_socket.

Get the native socket representation.

native_handle_type native_handle();

This function may be used to obtain the underlying representation of the socket. This is intended to allow access to native socket functionality that is not otherwise provided.

The native representation of a socket.

typedef StreamSocketService::native_handle_type native_handle_type;
Requirements

Header: boost/asio/basic_stream_socket.hpp

Convenience header: boost/asio.hpp

Gets the non-blocking mode of the native socket implementation.

bool native_non_blocking() const;
  » more...

Sets the non-blocking mode of the native socket implementation.

void native_non_blocking(
    bool mode);
  » more...

boost::system::error_code native_non_blocking(
    bool mode,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Gets the non-blocking mode of the native socket implementation.

bool native_non_blocking() const;

This function is used to retrieve the non-blocking mode of the underlying native socket. This mode has no effect on the behaviour of the socket object's synchronous operations.

Return Value

true if the underlying socket is in non-blocking mode and direct system calls may fail with boost::asio::error::would_block (or the equivalent system error).

Remarks

The current non-blocking mode is cached by the socket object. Consequently, the return value may be incorrect if the non-blocking mode was set directly on the native socket.

Example

This function is intended to allow the encapsulation of arbitrary non-blocking system calls as asynchronous operations, in a way that is transparent to the user of the socket object. The following example illustrates how Linux's sendfile system call might be encapsulated:

template <typename Handler>
struct sendfile_op
{
  tcp::socket& sock_;
  int fd_;
  Handler handler_;
  off_t offset_;
  std::size_t total_bytes_transferred_;

  // Function call operator meeting WriteHandler requirements.
  // Used as the handler for the async_write_some operation.
  void operator()(boost::system::error_code ec, std::size_t)
  {
    // Put the underlying socket into non-blocking mode.
    if (!ec)
      if (!sock_.native_non_blocking())
        sock_.native_non_blocking(true, ec);

    if (!ec)
    {
      for (;;)
      {
        // Try the system call.
        errno = 0;
        int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536);
        ec = boost::system::error_code(n < 0 ? errno : 0,
            boost::asio::error::get_system_category());
        total_bytes_transferred_ += ec ? 0 : n;

        // Retry operation immediately if interrupted by signal.
        if (ec == boost::asio::error::interrupted)
          continue;

        // Check if we need to run the operation again.
        if (ec == boost::asio::error::would_block
            || ec == boost::asio::error::try_again)
        {
          // We have to wait for the socket to become ready again.
          sock_.async_write_some(boost::asio::null_buffers(), *this);
          return;
        }

        if (ec || n == 0)
        {
          // An error occurred, or we have reached the end of the file.
          // Either way we must exit the loop so we can call the handler.
          break;
        }

        // Loop around to try calling sendfile again.
      }
    }

    // Pass result back to user's handler.
    handler_(ec, total_bytes_transferred_);
  }
};

template <typename Handler>
void async_sendfile(tcp::socket& sock, int fd, Handler h)
{
  sendfile_op<Handler> op = { sock, fd, h, 0, 0 };
  sock.async_write_some(boost::asio::null_buffers(), op);
}

Inherited from basic_socket.

Sets the non-blocking mode of the native socket implementation.

void native_non_blocking(
    bool mode);

This function is used to modify the non-blocking mode of the underlying native socket. It has no effect on the behaviour of the socket object's synchronous operations.

Parameters

mode

If true, the underlying socket is put into non-blocking mode and direct system calls may fail with boost::asio::error::would_block (or the equivalent system error).

Exceptions

boost::system::system_error

Thrown on failure. If the mode is false, but the current value of non_blocking() is true, this function fails with boost::asio::error::invalid_argument, as the combination does not make sense.

Example

This function is intended to allow the encapsulation of arbitrary non-blocking system calls as asynchronous operations, in a way that is transparent to the user of the socket object. The following example illustrates how Linux's sendfile system call might be encapsulated:

template <typename Handler>
struct sendfile_op
{
  tcp::socket& sock_;
  int fd_;
  Handler handler_;
  off_t offset_;
  std::size_t total_bytes_transferred_;

  // Function call operator meeting WriteHandler requirements.
  // Used as the handler for the async_write_some operation.
  void operator()(boost::system::error_code ec, std::size_t)
  {
    // Put the underlying socket into non-blocking mode.
    if (!ec)
      if (!sock_.native_non_blocking())
        sock_.native_non_blocking(true, ec);

    if (!ec)
    {
      for (;;)
      {
        // Try the system call.
        errno = 0;
        int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536);
        ec = boost::system::error_code(n < 0 ? errno : 0,
            boost::asio::error::get_system_category());
        total_bytes_transferred_ += ec ? 0 : n;

        // Retry operation immediately if interrupted by signal.
        if (ec == boost::asio::error::interrupted)
          continue;

        // Check if we need to run the operation again.
        if (ec == boost::asio::error::would_block
            || ec == boost::asio::error::try_again)
        {
          // We have to wait for the socket to become ready again.
          sock_.async_write_some(boost::asio::null_buffers(), *this);
          return;
        }

        if (ec || n == 0)
        {
          // An error occurred, or we have reached the end of the file.
          // Either way we must exit the loop so we can call the handler.
          break;
        }

        // Loop around to try calling sendfile again.
      }
    }

    // Pass result back to user's handler.
    handler_(ec, total_bytes_transferred_);
  }
};

template <typename Handler>
void async_sendfile(tcp::socket& sock, int fd, Handler h)
{
  sendfile_op<Handler> op = { sock, fd, h, 0, 0 };
  sock.async_write_some(boost::asio::null_buffers(), op);
}

Inherited from basic_socket.

Sets the non-blocking mode of the native socket implementation.

boost::system::error_code native_non_blocking(
    bool mode,
    boost::system::error_code & ec);

This function is used to modify the non-blocking mode of the underlying native socket. It has no effect on the behaviour of the socket object's synchronous operations.

Parameters

mode

If true, the underlying socket is put into non-blocking mode and direct system calls may fail with boost::asio::error::would_block (or the equivalent system error).

ec

Set to indicate what error occurred, if any. If the mode is false, but the current value of non_blocking() is true, this function fails with boost::asio::error::invalid_argument, as the combination does not make sense.

Example

This function is intended to allow the encapsulation of arbitrary non-blocking system calls as asynchronous operations, in a way that is transparent to the user of the socket object. The following example illustrates how Linux's sendfile system call might be encapsulated:

template <typename Handler>
struct sendfile_op
{
  tcp::socket& sock_;
  int fd_;
  Handler handler_;
  off_t offset_;
  std::size_t total_bytes_transferred_;

  // Function call operator meeting WriteHandler requirements.
  // Used as the handler for the async_write_some operation.
  void operator()(boost::system::error_code ec, std::size_t)
  {
    // Put the underlying socket into non-blocking mode.
    if (!ec)
      if (!sock_.native_non_blocking())
        sock_.native_non_blocking(true, ec);

    if (!ec)
    {
      for (;;)
      {
        // Try the system call.
        errno = 0;
        int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536);
        ec = boost::system::error_code(n < 0 ? errno : 0,
            boost::asio::error::get_system_category());
        total_bytes_transferred_ += ec ? 0 : n;

        // Retry operation immediately if interrupted by signal.
        if (ec == boost::asio::error::interrupted)
          continue;

        // Check if we need to run the operation again.
        if (ec == boost::asio::error::would_block
            || ec == boost::asio::error::try_again)
        {
          // We have to wait for the socket to become ready again.
          sock_.async_write_some(boost::asio::null_buffers(), *this);
          return;
        }

        if (ec || n == 0)
        {
          // An error occurred, or we have reached the end of the file.
          // Either way we must exit the loop so we can call the handler.
          break;
        }

        // Loop around to try calling sendfile again.
      }
    }

    // Pass result back to user's handler.
    handler_(ec, total_bytes_transferred_);
  }
};

template <typename Handler>
void async_sendfile(tcp::socket& sock, int fd, Handler h)
{
  sendfile_op<Handler> op = { sock, fd, h, 0, 0 };
  sock.async_write_some(boost::asio::null_buffers(), op);
}

(Deprecated: Use native_handle_type.) The native representation of a socket.

typedef StreamSocketService::native_handle_type native_type;
Requirements

Header: boost/asio/basic_stream_socket.hpp

Convenience header: boost/asio.hpp

Gets the non-blocking mode of the socket.

bool non_blocking() const;
  » more...

Sets the non-blocking mode of the socket.

void non_blocking(
    bool mode);
  » more...

boost::system::error_code non_blocking(
    bool mode,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Gets the non-blocking mode of the socket.

bool non_blocking() const;
Return Value

true if the socket's synchronous operations will fail with boost::asio::error::would_block if they are unable to perform the requested operation immediately. If false, synchronous operations will block until complete.

Remarks

The non-blocking mode has no effect on the behaviour of asynchronous operations. Asynchronous operations will never fail with the error boost::asio::error::would_block.

Inherited from basic_socket.

Sets the non-blocking mode of the socket.

void non_blocking(
    bool mode);
Parameters

mode

If true, the socket's synchronous operations will fail with boost::asio::error::would_block if they are unable to perform the requested operation immediately. If false, synchronous operations will block until complete.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

The non-blocking mode has no effect on the behaviour of asynchronous operations. Asynchronous operations will never fail with the error boost::asio::error::would_block.

Inherited from basic_socket.

Sets the non-blocking mode of the socket.

boost::system::error_code non_blocking(
    bool mode,
    boost::system::error_code & ec);
Parameters

mode

If true, the socket's synchronous operations will fail with boost::asio::error::would_block if they are unable to perform the requested operation immediately. If false, synchronous operations will block until complete.

ec

Set to indicate what error occurred, if any.

Remarks

The non-blocking mode has no effect on the behaviour of asynchronous operations. Asynchronous operations will never fail with the error boost::asio::error::would_block.

Inherited from socket_base.

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

typedef implementation_defined non_blocking_io;

Implements the FIONBIO IO control command.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::non_blocking_io command(true);
socket.io_control(command);
Requirements

Header: boost/asio/basic_stream_socket.hpp

Convenience header: boost/asio.hpp

Open the socket using the specified protocol.

void open(
    const protocol_type & protocol = protocol_type());
  » more...

boost::system::error_code open(
    const protocol_type & protocol,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Open the socket using the specified protocol.

void open(
    const protocol_type & protocol = protocol_type());

This function opens the socket so that it will use the specified protocol.

Parameters

protocol

An object specifying protocol parameters to be used.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::socket socket(io_service);
socket.open(boost::asio::ip::tcp::v4());

Inherited from basic_socket.

Open the socket using the specified protocol.

boost::system::error_code open(
    const protocol_type & protocol,
    boost::system::error_code & ec);

This function opens the socket so that it will use the specified protocol.

Parameters

protocol

An object specifying which protocol is to be used.

ec

Set to indicate what error occurred, if any.

Example
boost::asio::ip::tcp::socket socket(io_service);
boost::system::error_code ec;
socket.open(boost::asio::ip::tcp::v4(), ec);
if (ec)
{
  // An error occurred.
}

Move-assign a basic_stream_socket from another.

basic_stream_socket & operator=(
    basic_stream_socket && other);
  » more...

Move-assign a basic_stream_socket from a socket of another protocol type.

template<
    typename Protocol1,
    typename StreamSocketService1>
enable_if< is_convertible< Protocol1, Protocol >::value, basic_stream_socket >::type & operator=(
    basic_stream_socket< Protocol1, StreamSocketService1 > && other);
  » more...

Move-assign a basic_stream_socket from another.

basic_stream_socket & operator=(
    basic_stream_socket && other);

This assignment operator moves a stream socket from one object to another.

Parameters

other

The other basic_stream_socket object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_stream_socket(io_service&) constructor.

Move-assign a basic_stream_socket from a socket of another protocol type.

template<
    typename Protocol1,
    typename StreamSocketService1>
enable_if< is_convertible< Protocol1, Protocol >::value, basic_stream_socket >::type & operator=(
    basic_stream_socket< Protocol1, StreamSocketService1 > && other);

This assignment operator moves a stream socket from one object to another.

Parameters

other

The other basic_stream_socket object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_stream_socket(io_service&) constructor.

The protocol type.

typedef Protocol protocol_type;
Requirements

Header: boost/asio/basic_stream_socket.hpp

Convenience header: boost/asio.hpp

Read some data from the socket.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers);
  » more...

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);
  » more...

Read some data from the socket.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers);

This function is used to read data from the stream socket. The function call will block until one or more bytes of data has been read successfully, or until an error occurs.

Parameters

buffers

One or more buffers into which the data will be read.

Return Value

The number of bytes read.

Exceptions

boost::system::system_error

Thrown on failure. An error code of boost::asio::error::eof indicates that the connection was closed by the peer.

Remarks

The read_some operation may not read all of the requested number of bytes. Consider using the read function if you need to ensure that the requested amount of data is read before the blocking operation completes.

Example

To read into a single data buffer use the buffer function as follows:

socket.read_some(boost::asio::buffer(data, size));

See the buffer documentation for information on reading into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Read some data from the socket.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);

This function is used to read data from the stream socket. The function call will block until one or more bytes of data has been read successfully, or until an error occurs.

Parameters

buffers

One or more buffers into which the data will be read.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes read. Returns 0 if an error occurred.

Remarks

The read_some operation may not read all of the requested number of bytes. Consider using the read function if you need to ensure that the requested amount of data is read before the blocking operation completes.

Receive some data on the socket.

template<
    typename MutableBufferSequence>
std::size_t receive(
    const MutableBufferSequence & buffers);
  » more...

template<
    typename MutableBufferSequence>
std::size_t receive(
    const MutableBufferSequence & buffers,
    socket_base::message_flags flags);
  » more...

Receive some data on a connected socket.

template<
    typename MutableBufferSequence>
std::size_t receive(
    const MutableBufferSequence & buffers,
    socket_base::message_flags flags,
    boost::system::error_code & ec);
  » more...

Receive some data on the socket.

template<
    typename MutableBufferSequence>
std::size_t receive(
    const MutableBufferSequence & buffers);

This function is used to receive data on the stream socket. The function call will block until one or more bytes of data has been received successfully, or until an error occurs.

Parameters

buffers

One or more buffers into which the data will be received.

Return Value

The number of bytes received.

Exceptions

boost::system::system_error

Thrown on failure. An error code of boost::asio::error::eof indicates that the connection was closed by the peer.

Remarks

The receive operation may not receive all of the requested number of bytes. Consider using the read function if you need to ensure that the requested amount of data is read before the blocking operation completes.

Example

To receive into a single data buffer use the buffer function as follows:

socket.receive(boost::asio::buffer(data, size));

See the buffer documentation for information on receiving into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Receive some data on the socket.

template<
    typename MutableBufferSequence>
std::size_t receive(
    const MutableBufferSequence & buffers,
    socket_base::message_flags flags);

This function is used to receive data on the stream socket. The function call will block until one or more bytes of data has been received successfully, or until an error occurs.

Parameters

buffers

One or more buffers into which the data will be received.

flags

Flags specifying how the receive call is to be made.

Return Value

The number of bytes received.

Exceptions

boost::system::system_error

Thrown on failure. An error code of boost::asio::error::eof indicates that the connection was closed by the peer.

Remarks

The receive operation may not receive all of the requested number of bytes. Consider using the read function if you need to ensure that the requested amount of data is read before the blocking operation completes.

Example

To receive into a single data buffer use the buffer function as follows:

socket.receive(boost::asio::buffer(data, size), 0);

See the buffer documentation for information on receiving into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Receive some data on a connected socket.

template<
    typename MutableBufferSequence>
std::size_t receive(
    const MutableBufferSequence & buffers,
    socket_base::message_flags flags,
    boost::system::error_code & ec);

This function is used to receive data on the stream socket. The function call will block until one or more bytes of data has been received successfully, or until an error occurs.

Parameters

buffers

One or more buffers into which the data will be received.

flags

Flags specifying how the receive call is to be made.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes received. Returns 0 if an error occurred.

Remarks

The receive operation may not receive all of the requested number of bytes. Consider using the read function if you need to ensure that the requested amount of data is read before the blocking operation completes.

Inherited from socket_base.

Socket option for the receive buffer size of a socket.

typedef implementation_defined receive_buffer_size;

Implements the SOL_SOCKET/SO_RCVBUF socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_buffer_size option(8192);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_buffer_size option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/basic_stream_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option for the receive low watermark.

typedef implementation_defined receive_low_watermark;

Implements the SOL_SOCKET/SO_RCVLOWAT socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_low_watermark option(1024);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_low_watermark option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/basic_stream_socket.hpp

Convenience header: boost/asio.hpp

Get the remote endpoint of the socket.

endpoint_type remote_endpoint() const;
  » more...

endpoint_type remote_endpoint(
    boost::system::error_code & ec) const;
  » more...

Inherited from basic_socket.

Get the remote endpoint of the socket.

endpoint_type remote_endpoint() const;

This function is used to obtain the remote endpoint of the socket.

Return Value

An object that represents the remote endpoint of the socket.

Exceptions

boost::system::system_error

Thrown on failure.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::endpoint endpoint = socket.remote_endpoint();

Inherited from basic_socket.

Get the remote endpoint of the socket.

endpoint_type remote_endpoint(
    boost::system::error_code & ec) const;

This function is used to obtain the remote endpoint of the socket.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

An object that represents the remote endpoint of the socket. Returns a default-constructed endpoint object if an error occurred.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::system::error_code ec;
boost::asio::ip::tcp::endpoint endpoint = socket.remote_endpoint(ec);
if (ec)
{
  // An error occurred.
}

Inherited from socket_base.

Socket option to allow the socket to be bound to an address that is already in use.

typedef implementation_defined reuse_address;

Implements the SOL_SOCKET/SO_REUSEADDR socket option.

Examples

Setting the option:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::reuse_address option(true);
acceptor.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::reuse_address option;
acceptor.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/basic_stream_socket.hpp

Convenience header: boost/asio.hpp

Send some data on the socket.

template<
    typename ConstBufferSequence>
std::size_t send(
    const ConstBufferSequence & buffers);
  » more...

template<
    typename ConstBufferSequence>
std::size_t send(
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags);
  » more...

template<
    typename ConstBufferSequence>
std::size_t send(
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags,
    boost::system::error_code & ec);
  » more...

Send some data on the socket.

template<
    typename ConstBufferSequence>
std::size_t send(
    const ConstBufferSequence & buffers);

This function is used to send data on the stream socket. The function call will block until one or more bytes of the data has been sent successfully, or an until error occurs.

Parameters

buffers

One or more data buffers to be sent on the socket.

Return Value

The number of bytes sent.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

The send operation may not transmit all of the data to the peer. Consider using the write function if you need to ensure that all data is written before the blocking operation completes.

Example

To send a single data buffer use the buffer function as follows:

socket.send(boost::asio::buffer(data, size));

See the buffer documentation for information on sending multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Send some data on the socket.

template<
    typename ConstBufferSequence>
std::size_t send(
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags);

This function is used to send data on the stream socket. The function call will block until one or more bytes of the data has been sent successfully, or an until error occurs.

Parameters

buffers

One or more data buffers to be sent on the socket.

flags

Flags specifying how the send call is to be made.

Return Value

The number of bytes sent.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

The send operation may not transmit all of the data to the peer. Consider using the write function if you need to ensure that all data is written before the blocking operation completes.

Example

To send a single data buffer use the buffer function as follows:

socket.send(boost::asio::buffer(data, size), 0);

See the buffer documentation for information on sending multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Send some data on the socket.

template<
    typename ConstBufferSequence>
std::size_t send(
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags,
    boost::system::error_code & ec);

This function is used to send data on the stream socket. The function call will block until one or more bytes of the data has been sent successfully, or an until error occurs.

Parameters

buffers

One or more data buffers to be sent on the socket.

flags

Flags specifying how the send call is to be made.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes sent. Returns 0 if an error occurred.

Remarks

The send operation may not transmit all of the data to the peer. Consider using the write function if you need to ensure that all data is written before the blocking operation completes.

Inherited from socket_base.

Socket option for the send buffer size of a socket.

typedef implementation_defined send_buffer_size;

Implements the SOL_SOCKET/SO_SNDBUF socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_buffer_size option(8192);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_buffer_size option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/basic_stream_socket.hpp

Convenience header: boost/asio.hpp

Inherited from socket_base.

Socket option for the send low watermark.

typedef implementation_defined send_low_watermark;

Implements the SOL_SOCKET/SO_SNDLOWAT socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_low_watermark option(1024);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_low_watermark option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/basic_stream_socket.hpp

Convenience header: boost/asio.hpp

Inherited from basic_io_object.

(Deprecated: Use get_service().) The service associated with the I/O object.

service_type & service;
Remarks

Available only for services that do not support movability.

Inherited from basic_io_object.

The type of the service that will be used to provide I/O operations.

typedef StreamSocketService service_type;
Requirements

Header: boost/asio/basic_stream_socket.hpp

Convenience header: boost/asio.hpp

Set an option on the socket.

void set_option(
    const SettableSocketOption & option);
  » more...

boost::system::error_code set_option(
    const SettableSocketOption & option,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

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.

Parameters

option

The new option value to be set on the socket.

Exceptions

boost::system::system_error

Thrown on failure.

Example

Setting the IPPROTO_TCP/TCP_NODELAY option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::no_delay option(true);
socket.set_option(option);

Inherited from basic_socket.

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.

Parameters

option

The new option value to be set on the socket.

ec

Set to indicate what error occurred, if any.

Example

Setting the IPPROTO_TCP/TCP_NODELAY option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::no_delay option(true);
boost::system::error_code ec;
socket.set_option(option, ec);
if (ec)
{
  // An error occurred.
}

Disable sends or receives on the socket.

void shutdown(
    shutdown_type what);
  » more...

boost::system::error_code shutdown(
    shutdown_type what,
    boost::system::error_code & ec);
  » more...

Inherited from basic_socket.

Disable sends or receives on the socket.

void shutdown(
    shutdown_type what);

This function is used to disable send operations, receive operations, or both.

Parameters

what

Determines what types of operation will no longer be allowed.

Exceptions

boost::system::system_error

Thrown on failure.

Example

Shutting down the send side of the socket:

boost::asio::ip::tcp::socket socket(io_service);
...
socket.shutdown(boost::asio::ip::tcp::socket::shutdown_send);

Inherited from basic_socket.

Disable sends or receives on the socket.

boost::system::error_code shutdown(
    shutdown_type what,
    boost::system::error_code & ec);

This function is used to disable send operations, receive operations, or both.

Parameters

what

Determines what types of operation will no longer be allowed.

ec

Set to indicate what error occurred, if any.

Example

Shutting down the send side of the socket:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::system::error_code ec;
socket.shutdown(boost::asio::ip::tcp::socket::shutdown_send, ec);
if (ec)
{
  // An error occurred.
}

Inherited from socket_base.

Different ways a socket may be shutdown.

enum shutdown_type

Values

shutdown_receive

Shutdown the receive side of the socket.

shutdown_send

Shutdown the send side of the socket.

shutdown_both

Shutdown both send and receive on the socket.

Write some data to the socket.

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers);
  » more...

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers,
    boost::system::error_code & ec);
  » more...

Write some data to the socket.

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers);

This function is used to write data to the stream socket. The function call will block until one or more bytes of the data has been written successfully, or until an error occurs.

Parameters

buffers

One or more data buffers to be written to the socket.

Return Value

The number of bytes written.

Exceptions

boost::system::system_error

Thrown on failure. An error code of boost::asio::error::eof indicates that the connection was closed by the peer.

Remarks

The write_some operation may not transmit all of the data to the peer. Consider using the write function if you need to ensure that all data is written before the blocking operation completes.

Example

To write a single data buffer use the buffer function as follows:

socket.write_some(boost::asio::buffer(data, size));

See the buffer documentation for information on writing multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Write some data to the socket.

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers,
    boost::system::error_code & ec);

This function is used to write data to the stream socket. The function call will block until one or more bytes of the data has been written successfully, or until an error occurs.

Parameters

buffers

One or more data buffers to be written to the socket.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes written. Returns 0 if an error occurred.

Remarks

The write_some operation may not transmit all of the data to the peer. Consider using the write function if you need to ensure that all data is written before the blocking operation completes.

Automatically resizable buffer class based on std::streambuf.

template<
    typename Allocator = std::allocator<char>>
class basic_streambuf :
  noncopyable
Types

Name

Description

const_buffers_type

The type used to represent the input sequence as a list of buffers.

mutable_buffers_type

The type used to represent the output sequence as a list of buffers.

Member Functions

Name

Description

basic_streambuf

Construct a basic_streambuf object.

commit

Move characters from the output sequence to the input sequence.

consume

Remove characters from the input sequence.

data

Get a list of buffers that represents the input sequence.

max_size

Get the maximum size of the basic_streambuf.

prepare

Get a list of buffers that represents the output sequence, with the given size.

size

Get the size of the input sequence.

Protected Member Functions

Name

Description

overflow

Override std::streambuf behaviour.

reserve

underflow

Override std::streambuf behaviour.

The basic_streambuf class is derived from std::streambuf to associate the streambuf's input and output sequences with one or more character arrays. These character arrays are internal to the basic_streambuf object, but direct access to the array elements is provided to permit them to be used efficiently with I/O operations. Characters written to the output sequence of a basic_streambuf object are appended to the input sequence of the same object.

The basic_streambuf class's public interface is intended to permit the following implementation strategies:

  • A single contiguous character array, which is reallocated as necessary to accommodate changes in the size of the character sequence. This is the implementation approach currently used in Asio.
  • A sequence of one or more character arrays, where each array is of the same size. Additional character array objects are appended to the sequence to accommodate changes in the size of the character sequence.
  • A sequence of one or more character arrays of varying sizes. Additional character array objects are appended to the sequence to accommodate changes in the size of the character sequence.

The constructor for basic_streambuf accepts a size_t argument specifying the maximum of the sum of the sizes of the input sequence and output sequence. During the lifetime of the basic_streambuf object, the following invariant holds:

size() <= max_size()

Any member function that would, if successful, cause the invariant to be violated shall throw an exception of class std::length_error.

The constructor for basic_streambuf takes an Allocator argument. A copy of this argument is used for any memory allocation performed, by the constructor and by all member functions, during the lifetime of each basic_streambuf object.

Examples

Writing directly from an streambuf to a socket:

boost::asio::streambuf b;
std::ostream os(&b);
os << "Hello, World!\n";

// try sending some data in input sequence
size_t n = sock.send(b.data());

b.consume(n); // sent data is removed from input sequence

Reading from a socket directly into a streambuf:

boost::asio::streambuf b;

// reserve 512 bytes in output sequence
boost::asio::streambuf::mutable_buffers_type bufs = b.prepare(512);

size_t n = sock.receive(bufs);

// received data is "committed" from output sequence to input sequence
b.commit(n);

std::istream is(&b);
std::string s;
is >> s;
Requirements

Header: boost/asio/basic_streambuf.hpp

Convenience header: boost/asio.hpp

Construct a basic_streambuf object.

basic_streambuf(
    std::size_t maximum_size = (std::numeric_limits< std::size_t >::max)(),
    const Allocator & allocator = Allocator());

Constructs a streambuf with the specified maximum size. The initial size of the streambuf's input sequence is 0.

Move characters from the output sequence to the input sequence.

void commit(
    std::size_t n);

Appends n characters from the start of the output sequence to the input sequence. The beginning of the output sequence is advanced by n characters.

Requires a preceding call prepare(x) where x >= n, and no intervening operations that modify the input or output sequence.

Remarks

If n is greater than the size of the output sequence, the entire output sequence is moved to the input sequence and no error is issued.

The type used to represent the input sequence as a list of buffers.

typedef implementation_defined const_buffers_type;
Requirements

Header: boost/asio/basic_streambuf.hpp

Convenience header: boost/asio.hpp

Remove characters from the input sequence.

void consume(
    std::size_t n);

Removes n characters from the beginning of the input sequence.

Remarks

If n is greater than the size of the input sequence, the entire input sequence is consumed and no error is issued.

Get a list of buffers that represents the input sequence.

const_buffers_type data() const;
Return Value

An object of type const_buffers_type that satisfies ConstBufferSequence requirements, representing all character arrays in the input sequence.

Remarks

The returned object is invalidated by any basic_streambuf member function that modifies the input sequence or output sequence.

Get the maximum size of the basic_streambuf.

std::size_t max_size() const;
Return Value

The allowed maximum of the sum of the sizes of the input sequence and output sequence.

The type used to represent the output sequence as a list of buffers.

typedef implementation_defined mutable_buffers_type;
Requirements

Header: boost/asio/basic_streambuf.hpp

Convenience header: boost/asio.hpp

Override std::streambuf behaviour.

int_type overflow(
    int_type c);

Behaves according to the specification of std::streambuf::overflow(), with the specialisation that std::length_error is thrown if appending the character to the input sequence would require the condition size() > max_size() to be true.

Get a list of buffers that represents the output sequence, with the given size.

mutable_buffers_type prepare(
    std::size_t n);

Ensures that the output sequence can accommodate n characters, reallocating character array objects as necessary.

Return Value

An object of type mutable_buffers_type that satisfies MutableBufferSequence requirements, representing character array objects at the start of the output sequence such that the sum of the buffer sizes is n.

Exceptions

std::length_error

If size() + n > max_size().

Remarks

The returned object is invalidated by any basic_streambuf member function that modifies the input sequence or output sequence.

void reserve(
    std::size_t n);

Get the size of the input sequence.

std::size_t size() const;
Return Value

The size of the input sequence. The value is equal to that calculated for s in the following code:

size_t s = 0;
const_buffers_type bufs = data();
const_buffers_type::const_iterator i = bufs.begin();
while (i != bufs.end())
{
  const_buffer buf(*i++);
  s += buffer_size(buf);
}

Override std::streambuf behaviour.

int_type underflow();

Behaves according to the specification of std::streambuf::underflow().

Provides waitable timer functionality.

template<
    typename Clock,
    typename WaitTraits = boost::asio::wait_traits<Clock>,
    typename WaitableTimerService = waitable_timer_service<Clock, WaitTraits>>
class basic_waitable_timer :
  public basic_io_object< WaitableTimerService >
Types

Name

Description

clock_type

The clock type.

duration

The duration type of the clock.

implementation_type

The underlying implementation type of I/O object.

service_type

The type of the service that will be used to provide I/O operations.

time_point

The time point type of the clock.

traits_type

The wait traits type.

Member Functions

Name

Description

async_wait

Start an asynchronous wait on the timer.

basic_waitable_timer

Constructor.

Constructor to set a particular expiry time as an absolute time.

Constructor to set a particular expiry time relative to now.

cancel

Cancel any asynchronous operations that are waiting on the timer.

cancel_one

Cancels one asynchronous operation that is waiting on the timer.

expires_at

Get the timer's expiry time as an absolute time.

Set the timer's expiry time as an absolute time.

expires_from_now

Get the timer's expiry time relative to now.

Set the timer's expiry time relative to now.

get_io_service

Get the io_service associated with the object.

wait

Perform a blocking wait on the timer.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_waitable_timer class template provides the ability to perform a blocking or asynchronous wait for a timer to expire.

A waitable timer is always in one of two states: "expired" or "not expired". If the wait() or async_wait() function is called on an expired timer, the wait operation will complete immediately.

Most applications will use one of the steady_timer, system_timer or high_resolution_timer typedefs.

Remarks

This waitable timer functionality is for use with the C++11 standard library's <chrono> facility, or with the Boost.Chrono library.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Examples

Performing a blocking wait (C++11):

// Construct a timer without setting an expiry time.
boost::asio::steady_timer timer(io_service);

// Set an expiry time relative to now.
timer.expires_from_now(std::chrono::seconds(5));

// Wait for the timer to expire.
timer.wait();

Performing an asynchronous wait (C++11):

void handler(const boost::system::error_code& error)
{
  if (!error)
  {
    // Timer expired.
  }
}

...

// Construct a timer with an absolute expiry time.
boost::asio::steady_timer timer(io_service,
    std::chrono::steady_clock::now() + std::chrono::seconds(60));

// Start an asynchronous wait.
timer.async_wait(handler);
Changing an active waitable timer's expiry time

Changing the expiry time of a timer while there are pending asynchronous waits causes those wait operations to be cancelled. To ensure that the action associated with the timer is performed only once, use something like this: used:

void on_some_event()
{
  if (my_timer.expires_from_now(seconds(5)) > 0)
  {
    // We managed to cancel the timer. Start new asynchronous wait.
    my_timer.async_wait(on_timeout);
  }
  else
  {
    // Too late, timer has already expired!
  }
}

void on_timeout(const boost::system::error_code& e)
{
  if (e != boost::asio::error::operation_aborted)
  {
    // Timer was not cancelled, take necessary action.
  }
}
  • The boost::asio::basic_waitable_timer::expires_from_now() function cancels any pending asynchronous waits, and returns the number of asynchronous waits that were cancelled. If it returns 0 then you were too late and the wait handler has already been executed, or will soon be executed. If it returns 1 then the wait handler was successfully cancelled.
  • If a wait handler is cancelled, the boost::system::error_code passed to it contains the value boost::asio::error::operation_aborted.
Requirements

Header: boost/asio/basic_waitable_timer.hpp

Convenience header: boost/asio.hpp

Start an asynchronous wait on the timer.

template<
    typename WaitHandler>
void-or-deduced async_wait(
    WaitHandler handler);

This function may be used to initiate an asynchronous wait against the timer. It always returns immediately.

For each call to async_wait(), the supplied handler will be called exactly once. The handler will be called when:

  • The timer has expired.
  • The timer was cancelled, in which case the handler is passed the error code boost::asio::error::operation_aborted.
Parameters

handler

The handler to be called when the timer expires. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error // Result of operation.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Constructor.

explicit basic_waitable_timer(
    boost::asio::io_service & io_service);
  » more...

Constructor to set a particular expiry time as an absolute time.

basic_waitable_timer(
    boost::asio::io_service & io_service,
    const time_point & expiry_time);
  » more...

Constructor to set a particular expiry time relative to now.

basic_waitable_timer(
    boost::asio::io_service & io_service,
    const duration & expiry_time);
  » more...

Constructor.

basic_waitable_timer(
    boost::asio::io_service & io_service);

This constructor creates a timer without setting an expiry time. The expires_at() or expires_from_now() functions must be called to set an expiry time before the timer can be waited on.

Parameters

io_service

The io_service object that the timer will use to dispatch handlers for any asynchronous operations performed on the timer.

Constructor to set a particular expiry time as an absolute time.

basic_waitable_timer(
    boost::asio::io_service & io_service,
    const time_point & expiry_time);

This constructor creates a timer and sets the expiry time.

Parameters

io_service

The io_service object that the timer will use to dispatch handlers for any asynchronous operations performed on the timer.

expiry_time

The expiry time to be used for the timer, expressed as an absolute time.

Constructor to set a particular expiry time relative to now.

basic_waitable_timer(
    boost::asio::io_service & io_service,
    const duration & expiry_time);

This constructor creates a timer and sets the expiry time.

Parameters

io_service

The io_service object that the timer will use to dispatch handlers for any asynchronous operations performed on the timer.

expiry_time

The expiry time to be used for the timer, relative to now.

Cancel any asynchronous operations that are waiting on the timer.

std::size_t cancel();
  » more...

std::size_t cancel(
    boost::system::error_code & ec);
  » more...

Cancel any asynchronous operations that are waiting on the timer.

std::size_t cancel();

This function forces the completion of any pending asynchronous wait operations against the timer. The handler for each cancelled operation will be invoked with the boost::asio::error::operation_aborted error code.

Cancelling the timer does not change the expiry time.

Return Value

The number of asynchronous operations that were cancelled.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

If the timer has already expired when cancel() is called, then the handlers for asynchronous wait operations will:

  • have already been invoked; or
  • have been queued for invocation in the near future.

These handlers can no longer be cancelled, and therefore are passed an error code that indicates the successful completion of the wait operation.

Cancel any asynchronous operations that are waiting on the timer.

std::size_t cancel(
    boost::system::error_code & ec);

This function forces the completion of any pending asynchronous wait operations against the timer. The handler for each cancelled operation will be invoked with the boost::asio::error::operation_aborted error code.

Cancelling the timer does not change the expiry time.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

The number of asynchronous operations that were cancelled.

Remarks

If the timer has already expired when cancel() is called, then the handlers for asynchronous wait operations will:

  • have already been invoked; or
  • have been queued for invocation in the near future.

These handlers can no longer be cancelled, and therefore are passed an error code that indicates the successful completion of the wait operation.

Cancels one asynchronous operation that is waiting on the timer.

std::size_t cancel_one();
  » more...

std::size_t cancel_one(
    boost::system::error_code & ec);
  » more...

Cancels one asynchronous operation that is waiting on the timer.

std::size_t cancel_one();

This function forces the completion of one pending asynchronous wait operation against the timer. Handlers are cancelled in FIFO order. The handler for the cancelled operation will be invoked with the boost::asio::error::operation_aborted error code.

Cancelling the timer does not change the expiry time.

Return Value

The number of asynchronous operations that were cancelled. That is, either 0 or 1.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

If the timer has already expired when cancel_one() is called, then the handlers for asynchronous wait operations will:

  • have already been invoked; or
  • have been queued for invocation in the near future.

These handlers can no longer be cancelled, and therefore are passed an error code that indicates the successful completion of the wait operation.

Cancels one asynchronous operation that is waiting on the timer.

std::size_t cancel_one(
    boost::system::error_code & ec);

This function forces the completion of one pending asynchronous wait operation against the timer. Handlers are cancelled in FIFO order. The handler for the cancelled operation will be invoked with the boost::asio::error::operation_aborted error code.

Cancelling the timer does not change the expiry time.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

The number of asynchronous operations that were cancelled. That is, either 0 or 1.

Remarks

If the timer has already expired when cancel_one() is called, then the handlers for asynchronous wait operations will:

  • have already been invoked; or
  • have been queued for invocation in the near future.

These handlers can no longer be cancelled, and therefore are passed an error code that indicates the successful completion of the wait operation.

The clock type.

typedef Clock clock_type;
Requirements

Header: boost/asio/basic_waitable_timer.hpp

Convenience header: boost/asio.hpp

The duration type of the clock.

typedef clock_type::duration duration;
Requirements

Header: boost/asio/basic_waitable_timer.hpp

Convenience header: boost/asio.hpp

Get the timer's expiry time as an absolute time.

time_point expires_at() const;
  » more...

Set the timer's expiry time as an absolute time.

std::size_t expires_at(
    const time_point & expiry_time);
  » more...

std::size_t expires_at(
    const time_point & expiry_time,
    boost::system::error_code & ec);
  » more...

Get the timer's expiry time as an absolute time.

time_point expires_at() const;

This function may be used to obtain the timer's current expiry time. Whether the timer has expired or not does not affect this value.

Set the timer's expiry time as an absolute time.

std::size_t expires_at(
    const time_point & expiry_time);

This function sets the expiry time. Any pending asynchronous wait operations will be cancelled. The handler for each cancelled operation will be invoked with the boost::asio::error::operation_aborted error code.

Parameters

expiry_time

The expiry time to be used for the timer.

Return Value

The number of asynchronous operations that were cancelled.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

If the timer has already expired when expires_at() is called, then the handlers for asynchronous wait operations will:

  • have already been invoked; or
  • have been queued for invocation in the near future.

These handlers can no longer be cancelled, and therefore are passed an error code that indicates the successful completion of the wait operation.

Set the timer's expiry time as an absolute time.

std::size_t expires_at(
    const time_point & expiry_time,
    boost::system::error_code & ec);

This function sets the expiry time. Any pending asynchronous wait operations will be cancelled. The handler for each cancelled operation will be invoked with the boost::asio::error::operation_aborted error code.

Parameters

expiry_time

The expiry time to be used for the timer.

ec

Set to indicate what error occurred, if any.

Return Value

The number of asynchronous operations that were cancelled.

Remarks

If the timer has already expired when expires_at() is called, then the handlers for asynchronous wait operations will:

  • have already been invoked; or
  • have been queued for invocation in the near future.

These handlers can no longer be cancelled, and therefore are passed an error code that indicates the successful completion of the wait operation.

Get the timer's expiry time relative to now.

duration expires_from_now() const;
  » more...

Set the timer's expiry time relative to now.

std::size_t expires_from_now(
    const duration & expiry_time);
  » more...

std::size_t expires_from_now(
    const duration & expiry_time,
    boost::system::error_code & ec);
  » more...

Get the timer's expiry time relative to now.

duration expires_from_now() const;

This function may be used to obtain the timer's current expiry time. Whether the timer has expired or not does not affect this value.

Set the timer's expiry time relative to now.

std::size_t expires_from_now(
    const duration & expiry_time);

This function sets the expiry time. Any pending asynchronous wait operations will be cancelled. The handler for each cancelled operation will be invoked with the boost::asio::error::operation_aborted error code.

Parameters

expiry_time

The expiry time to be used for the timer.

Return Value

The number of asynchronous operations that were cancelled.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

If the timer has already expired when expires_from_now() is called, then the handlers for asynchronous wait operations will:

  • have already been invoked; or
  • have been queued for invocation in the near future.

These handlers can no longer be cancelled, and therefore are passed an error code that indicates the successful completion of the wait operation.

Set the timer's expiry time relative to now.

std::size_t expires_from_now(
    const duration & expiry_time,
    boost::system::error_code & ec);

This function sets the expiry time. Any pending asynchronous wait operations will be cancelled. The handler for each cancelled operation will be invoked with the boost::asio::error::operation_aborted error code.

Parameters

expiry_time

The expiry time to be used for the timer.

ec

Set to indicate what error occurred, if any.

Return Value

The number of asynchronous operations that were cancelled.

Remarks

If the timer has already expired when expires_from_now() is called, then the handlers for asynchronous wait operations will:

  • have already been invoked; or
  • have been queued for invocation in the near future.

These handlers can no longer be cancelled, and therefore are passed an error code that indicates the successful completion of the wait operation.

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();
  » more...

const implementation_type & get_implementation() const;
  » more...

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

const implementation_type & get_implementation() const;

Inherited from basic_io_object.

Get the io_service associated with the object.

boost::asio::io_service & get_io_service();

This function may be used to obtain the io_service object that the I/O object uses to dispatch handlers for asynchronous operations.

Return Value

A reference to the io_service object that the I/O object will use to dispatch handlers. Ownership is not transferred to the caller.

Get the service associated with the I/O object.

service_type & get_service();
  » more...

const service_type & get_service() const;
  » more...

Inherited from basic_io_object.

Get the service associated with the I/O object.

service_type & get_service();

Inherited from basic_io_object.

Get the service associated with the I/O object.

const service_type & get_service() const;

Inherited from basic_io_object.

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

implementation_type implementation;

Inherited from basic_io_object.

The underlying implementation type of I/O object.

typedef service_type::implementation_type implementation_type;
Requirements

Header: boost/asio/basic_waitable_timer.hpp

Convenience header: boost/asio.hpp

Inherited from basic_io_object.

(Deprecated: Use get_service().) The service associated with the I/O object.

service_type & service;
Remarks

Available only for services that do not support movability.

Inherited from basic_io_object.

The type of the service that will be used to provide I/O operations.

typedef WaitableTimerService service_type;
Requirements

Header: boost/asio/basic_waitable_timer.hpp

Convenience header: boost/asio.hpp

The time point type of the clock.

typedef clock_type::time_point time_point;
Requirements

Header: boost/asio/basic_waitable_timer.hpp

Convenience header: boost/asio.hpp

The wait traits type.

typedef WaitTraits traits_type;
Requirements

Header: boost/asio/basic_waitable_timer.hpp

Convenience header: boost/asio.hpp

Perform a blocking wait on the timer.

void wait();
  » more...

void wait(
    boost::system::error_code & ec);
  » more...

Perform a blocking wait on the timer.

void wait();

This function is used to wait for the timer to expire. This function blocks and does not return until the timer has expired.

Exceptions

boost::system::system_error

Thrown on failure.

Perform a blocking wait on the timer.

void wait(
    boost::system::error_code & ec);

This function is used to wait for the timer to expire. This function blocks and does not return until the timer has expired.

Parameters

ec

Set to indicate what error occurred, if any.

Context object the represents the currently executing coroutine.

template<
    typename Handler>
class basic_yield_context
Types

Name

Description

callee_type

The coroutine callee type, used by the implementation.

caller_type

The coroutine caller type, used by the implementation.

Member Functions

Name

Description

basic_yield_context

Construct a yield context to represent the specified coroutine.

operator[]

Return a yield context that sets the specified error_code.

The basic_yield_context class is used to represent the currently executing stackful coroutine. A basic_yield_context may be passed as a handler to an asynchronous operation. For example:

template <typename Handler>
void my_coroutine(basic_yield_context<Handler> yield)
{
  ...
  std::size_t n = my_socket.async_read_some(buffer, yield);
  ...
}

The initiating function (async_read_some in the above example) suspends the current coroutine. The coroutine is resumed when the asynchronous operation completes, and the result of the operation is returned.

Requirements

Header: boost/asio/spawn.hpp

Convenience header: None

Construct a yield context to represent the specified coroutine.

basic_yield_context(
    const detail::weak_ptr< callee_type > & coro,
    caller_type & ca,
    Handler & handler);

Most applications do not need to use this constructor. Instead, the spawn() function passes a yield context as an argument to the coroutine function.

The coroutine callee type, used by the implementation.

typedef implementation_defined callee_type;

When using Boost.Coroutine v1, this type is:

typename coroutine<void()>

When using Boost.Coroutine v2 (unidirectional coroutines), this type is:

push_coroutine<void>
Requirements

Header: boost/asio/spawn.hpp

Convenience header: None

The coroutine caller type, used by the implementation.

typedef implementation_defined caller_type;

When using Boost.Coroutine v1, this type is:

typename coroutine<void()>::caller_type

When using Boost.Coroutine v2 (unidirectional coroutines), this type is:

pull_coroutine<void>
Requirements

Header: boost/asio/spawn.hpp

Convenience header: None

Return a yield context that sets the specified error_code.

basic_yield_context operator[](
    boost::system::error_code & ec) const;

By default, when a yield context is used with an asynchronous operation, a non-success error_code is converted to system_error and thrown. This operator may be used to specify an error_code object that should instead be set with the asynchronous operation's result. For example:

template <typename Handler>
void my_coroutine(basic_yield_context<Handler> yield)
{
  ...
  std::size_t n = my_socket.async_read_some(buffer, yield[ec]);
  if (ec)
  {
    // An error occurred.
  }
  ...
}

The boost::asio::buffer function is used to create a buffer object to represent raw memory, an array of POD elements, a vector of POD elements, or a std::string.

mutable_buffers_1 buffer(
    const mutable_buffer & b);
  » more...

mutable_buffers_1 buffer(
    const mutable_buffer & b,
    std::size_t max_size_in_bytes);
  » more...

const_buffers_1 buffer(
    const const_buffer & b);
  » more...

const_buffers_1 buffer(
    const const_buffer & b,
    std::size_t max_size_in_bytes);
  » more...

mutable_buffers_1 buffer(
    void * data,
    std::size_t size_in_bytes);
  » more...

const_buffers_1 buffer(
    const void * data,
    std::size_t size_in_bytes);
  » more...

template<
    typename PodType,
    std::size_t N>
mutable_buffers_1 buffer(
    PodType (&data)[N]);
  » more...

template<
    typename PodType,
    std::size_t N>
mutable_buffers_1 buffer(
    PodType (&data)[N],
    std::size_t max_size_in_bytes);
  » more...

template<
    typename PodType,
    std::size_t N>
const_buffers_1 buffer(
    const PodType (&data)[N]);
  » more...

template<
    typename PodType,
    std::size_t N>
const_buffers_1 buffer(
    const PodType (&data)[N],
    std::size_t max_size_in_bytes);
  » more...

template<
    typename PodType,
    std::size_t N>
mutable_buffers_1 buffer(
    boost::array< PodType, N > & data);
  » more...

template<
    typename PodType,
    std::size_t N>
mutable_buffers_1 buffer(
    boost::array< PodType, N > & data,
    std::size_t max_size_in_bytes);
  » more...

template<
    typename PodType,
    std::size_t N>
const_buffers_1 buffer(
    boost::array< const PodType, N > & data);
  » more...

template<
    typename PodType,
    std::size_t N>
const_buffers_1 buffer(
    boost::array< const PodType, N > & data,
    std::size_t max_size_in_bytes);
  » more...

template<
    typename PodType,
    std::size_t N>
const_buffers_1 buffer(
    const boost::array< PodType, N > & data);
  » more...

template<
    typename PodType,
    std::size_t N>
const_buffers_1 buffer(
    const boost::array< PodType, N > & data,
    std::size_t max_size_in_bytes);
  » more...

template<
    typename PodType,
    std::size_t N>
mutable_buffers_1 buffer(
    std::array< PodType, N > & data);
  » more...

template<
    typename PodType,
    std::size_t N>
mutable_buffers_1 buffer(
    std::array< PodType, N > & data,
    std::size_t max_size_in_bytes);
  » more...

template<
    typename PodType,
    std::size_t N>
const_buffers_1 buffer(
    std::array< const PodType, N > & data);
  » more...

template<
    typename PodType,
    std::size_t N>
const_buffers_1 buffer(
    std::array< const PodType, N > & data,
    std::size_t max_size_in_bytes);
  » more...

template<
    typename PodType,
    std::size_t N>
const_buffers_1 buffer(
    const std::array< PodType, N > & data);
  » more...

template<
    typename PodType,
    std::size_t N>
const_buffers_1 buffer(
    const std::array< PodType, N > & data,
    std::size_t max_size_in_bytes);
  » more...

template<
    typename PodType,
    typename Allocator>
mutable_buffers_1 buffer(
    std::vector< PodType, Allocator > & data);
  » more...

template<
    typename PodType,
    typename Allocator>
mutable_buffers_1 buffer(
    std::vector< PodType, Allocator > & data,
    std::size_t max_size_in_bytes);
  » more...

template<
    typename PodType,
    typename Allocator>
const_buffers_1 buffer(
    const std::vector< PodType, Allocator > & data);
  » more...

template<
    typename PodType,
    typename Allocator>
const_buffers_1 buffer(
    const std::vector< PodType, Allocator > & data,
    std::size_t max_size_in_bytes);
  » more...

template<
    typename Elem,
    typename Traits,
    typename Allocator>
const_buffers_1 buffer(
    const std::basic_string< Elem, Traits, Allocator > & data);
  » more...

template<
    typename Elem,
    typename Traits,
    typename Allocator>
const_buffers_1 buffer(
    const std::basic_string< Elem, Traits, Allocator > & data,
    std::size_t max_size_in_bytes);
  » more...

A buffer object represents a contiguous region of memory as a 2-tuple consisting of a pointer and size in bytes. A tuple of the form {void*, size_t} specifies a mutable (modifiable) region of memory. Similarly, a tuple of the form {const void*, size_t} specifies a const (non-modifiable) region of memory. These two forms correspond to the classes mutable_buffer and const_buffer, respectively. To mirror C++'s conversion rules, a mutable_buffer is implicitly convertible to a const_buffer, and the opposite conversion is not permitted.

The simplest use case involves reading or writing a single buffer of a specified size:

sock.send(boost::asio::buffer(data, size));

In the above example, the return value of boost::asio::buffer meets the requirements of the ConstBufferSequence concept so that it may be directly passed to the socket's write function. A buffer created for modifiable memory also meets the requirements of the MutableBufferSequence concept.

An individual buffer may be created from a builtin array, std::vector, std::array or boost::array of POD elements. This helps prevent buffer overruns by automatically determining the size of the buffer:

char d1[128];
size_t bytes_transferred = sock.receive(boost::asio::buffer(d1));

std::vector<char> d2(128);
bytes_transferred = sock.receive(boost::asio::buffer(d2));

std::array<char, 128> d3;
bytes_transferred = sock.receive(boost::asio::buffer(d3));

boost::array<char, 128> d4;
bytes_transferred = sock.receive(boost::asio::buffer(d4));

In all three cases above, the buffers created are exactly 128 bytes long. Note that a vector is never automatically resized when creating or using a buffer. The buffer size is determined using the vector's size() member function, and not its capacity.

Accessing Buffer Contents

The contents of a buffer may be accessed using the buffer_size and buffer_cast functions:

boost::asio::mutable_buffer b1 = ...;
std::size_t s1 = boost::asio::buffer_size(b1);
unsigned char* p1 = boost::asio::buffer_cast<unsigned char*>(b1);

boost::asio::const_buffer b2 = ...;
std::size_t s2 = boost::asio::buffer_size(b2);
const void* p2 = boost::asio::buffer_cast<const void*>(b2);

The boost::asio::buffer_cast function permits violations of type safety, so uses of it in application code should be carefully considered.

For convenience, the buffer_size function also works on buffer sequences (that is, types meeting the ConstBufferSequence or MutableBufferSequence type requirements). In this case, the function returns the total size of all buffers in the sequence.

Buffer Copying

The buffer_copy function may be used to copy raw bytes between individual buffers and buffer sequences.

In particular, when used with the buffer_size , the buffer_copy function can be used to linearise a sequence of buffers. For example:

vector<const_buffer> buffers = ...;

vector<unsigned char> data(boost::asio::buffer_size(buffers));
boost::asio::buffer_copy(boost::asio::buffer(data), buffers);

Note that buffer_copy is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Buffer Invalidation

A buffer object does not have any ownership of the memory it refers to. It is the responsibility of the application to ensure the memory region remains valid until it is no longer required for an I/O operation. When the memory is no longer available, the buffer is said to have been invalidated.

For the boost::asio::buffer overloads that accept an argument of type std::vector, the buffer objects returned are invalidated by any vector operation that also invalidates all references, pointers and iterators referring to the elements in the sequence (C++ Std, 23.2.4)

For the boost::asio::buffer overloads that accept an argument of type std::basic_string, the buffer objects returned are invalidated according to the rules defined for invalidation of references, pointers and iterators referring to elements of the sequence (C++ Std, 21.3).

Buffer Arithmetic

Buffer objects may be manipulated using simple arithmetic in a safe way which helps prevent buffer overruns. Consider an array initialised as follows:

boost::array<char, 6> a = { 'a', 'b', 'c', 'd', 'e' };

A buffer object b1 created using:

b1 = boost::asio::buffer(a);

represents the entire array, { 'a', 'b', 'c', 'd', 'e' }. An optional second argument to the boost::asio::buffer function may be used to limit the size, in bytes, of the buffer:

b2 = boost::asio::buffer(a, 3);

such that b2 represents the data { 'a', 'b', 'c' }. Even if the size argument exceeds the actual size of the array, the size of the buffer object created will be limited to the array size.

An offset may be applied to an existing buffer to create a new one:

b3 = b1 + 2;

where b3 will set to represent { 'c', 'd', 'e' }. If the offset exceeds the size of the existing buffer, the newly created buffer will be empty.

Both an offset and size may be specified to create a buffer that corresponds to a specific range of bytes within an existing buffer:

b4 = boost::asio::buffer(b1 + 1, 3);

so that b4 will refer to the bytes { 'b', 'c', 'd' }.

Buffers and Scatter-Gather I/O

To read or write using multiple buffers (i.e. scatter-gather I/O), multiple buffer objects may be assigned into a container that supports the MutableBufferSequence (for read) or ConstBufferSequence (for write) concepts:

char d1[128];
std::vector<char> d2(128);
boost::array<char, 128> d3;

boost::array<mutable_buffer, 3> bufs1 = {
  boost::asio::buffer(d1),
  boost::asio::buffer(d2),
  boost::asio::buffer(d3) };
bytes_transferred = sock.receive(bufs1);

std::vector<const_buffer> bufs2;
bufs2.push_back(boost::asio::buffer(d1));
bufs2.push_back(boost::asio::buffer(d2));
bufs2.push_back(boost::asio::buffer(d3));
bytes_transferred = sock.send(bufs2);
Requirements

Header: boost/asio/buffer.hpp

Convenience header: boost/asio.hpp

Create a new modifiable buffer from an existing buffer.

mutable_buffers_1 buffer(
    const mutable_buffer & b);
Return Value

mutable_buffers_1(b).

Create a new modifiable buffer from an existing buffer.

mutable_buffers_1 buffer(
    const mutable_buffer & b,
    std::size_t max_size_in_bytes);
Return Value

A mutable_buffers_1 value equivalent to:

mutable_buffers_1(
    buffer_cast<void*>(b),
    min(buffer_size(b), max_size_in_bytes));

Create a new non-modifiable buffer from an existing buffer.

const_buffers_1 buffer(
    const const_buffer & b);
Return Value

const_buffers_1(b).

Create a new non-modifiable buffer from an existing buffer.

const_buffers_1 buffer(
    const const_buffer & b,
    std::size_t max_size_in_bytes);
Return Value

A const_buffers_1 value equivalent to:

const_buffers_1(
    buffer_cast<const void*>(b),
    min(buffer_size(b), max_size_in_bytes));

Create a new modifiable buffer that represents the given memory range.

mutable_buffers_1 buffer(
    void * data,
    std::size_t size_in_bytes);
Return Value

mutable_buffers_1(data, size_in_bytes).

Create a new non-modifiable buffer that represents the given memory range.

const_buffers_1 buffer(
    const void * data,
    std::size_t size_in_bytes);
Return Value

const_buffers_1(data, size_in_bytes).

Create a new modifiable buffer that represents the given POD array.

template<
    typename PodType,
    std::size_t N>
mutable_buffers_1 buffer(
    PodType (&data)[N]);
Return Value

A mutable_buffers_1 value equivalent to:

mutable_buffers_1(
    static_cast<void*>(data),
    N * sizeof(PodType));

Create a new modifiable buffer that represents the given POD array.

template<
    typename PodType,
    std::size_t N>
mutable_buffers_1 buffer(
    PodType (&data)[N],
    std::size_t max_size_in_bytes);
Return Value

A mutable_buffers_1 value equivalent to:

mutable_buffers_1(
    static_cast<void*>(data),
    min(N * sizeof(PodType), max_size_in_bytes));

Create a new non-modifiable buffer that represents the given POD array.

template<
    typename PodType,
    std::size_t N>
const_buffers_1 buffer(
    const PodType (&data)[N]);
Return Value

A const_buffers_1 value equivalent to:

const_buffers_1(
    static_cast<const void*>(data),
    N * sizeof(PodType));

Create a new non-modifiable buffer that represents the given POD array.

template<
    typename PodType,
    std::size_t N>
const_buffers_1 buffer(
    const PodType (&data)[N],
    std::size_t max_size_in_bytes);
Return Value

A const_buffers_1 value equivalent to:

const_buffers_1(
    static_cast<const void*>(data),
    min(N * sizeof(PodType), max_size_in_bytes));

Create a new modifiable buffer that represents the given POD array.

template<
    typename PodType,
    std::size_t N>
mutable_buffers_1 buffer(
    boost::array< PodType, N > & data);
Return Value

A mutable_buffers_1 value equivalent to:

mutable_buffers_1(
    data.data(),
    data.size() * sizeof(PodType));

Create a new modifiable buffer that represents the given POD array.

template<
    typename PodType,
    std::size_t N>
mutable_buffers_1 buffer(
    boost::array< PodType, N > & data,
    std::size_t max_size_in_bytes);
Return Value

A mutable_buffers_1 value equivalent to:

mutable_buffers_1(
    data.data(),
    min(data.size() * sizeof(PodType), max_size_in_bytes));

Create a new non-modifiable buffer that represents the given POD array.

template<
    typename PodType,
    std::size_t N>
const_buffers_1 buffer(
    boost::array< const PodType, N > & data);
Return Value

A const_buffers_1 value equivalent to:

const_buffers_1(
    data.data(),
    data.size() * sizeof(PodType));

Create a new non-modifiable buffer that represents the given POD array.

template<
    typename PodType,
    std::size_t N>
const_buffers_1 buffer(
    boost::array< const PodType, N > & data,
    std::size_t max_size_in_bytes);
Return Value

A const_buffers_1 value equivalent to:

const_buffers_1(
    data.data(),
    min(data.size() * sizeof(PodType), max_size_in_bytes));

Create a new non-modifiable buffer that represents the given POD array.

template<
    typename PodType,
    std::size_t N>
const_buffers_1 buffer(
    const boost::array< PodType, N > & data);
Return Value

A const_buffers_1 value equivalent to:

const_buffers_1(
    data.data(),
    data.size() * sizeof(PodType));

Create a new non-modifiable buffer that represents the given POD array.

template<
    typename PodType,
    std::size_t N>
const_buffers_1 buffer(
    const boost::array< PodType, N > & data,
    std::size_t max_size_in_bytes);
Return Value

A const_buffers_1 value equivalent to:

const_buffers_1(
    data.data(),
    min(data.size() * sizeof(PodType), max_size_in_bytes));

Create a new modifiable buffer that represents the given POD array.

template<
    typename PodType,
    std::size_t N>
mutable_buffers_1 buffer(
    std::array< PodType, N > & data);
Return Value

A mutable_buffers_1 value equivalent to:

mutable_buffers_1(
    data.data(),
    data.size() * sizeof(PodType));

Create a new modifiable buffer that represents the given POD array.

template<
    typename PodType,
    std::size_t N>
mutable_buffers_1 buffer(
    std::array< PodType, N > & data,
    std::size_t max_size_in_bytes);
Return Value

A mutable_buffers_1 value equivalent to:

mutable_buffers_1(
    data.data(),
    min(data.size() * sizeof(PodType), max_size_in_bytes));

Create a new non-modifiable buffer that represents the given POD array.

template<
    typename PodType,
    std::size_t N>
const_buffers_1 buffer(
    std::array< const PodType, N > & data);
Return Value

A const_buffers_1 value equivalent to:

const_buffers_1(
    data.data(),
    data.size() * sizeof(PodType));

Create a new non-modifiable buffer that represents the given POD array.

template<
    typename PodType,
    std::size_t N>
const_buffers_1 buffer(
    std::array< const PodType, N > & data,
    std::size_t max_size_in_bytes);
Return Value

A const_buffers_1 value equivalent to:

const_buffers_1(
    data.data(),
    min(data.size() * sizeof(PodType), max_size_in_bytes));

Create a new non-modifiable buffer that represents the given POD array.

template<
    typename PodType,
    std::size_t N>
const_buffers_1 buffer(
    const std::array< PodType, N > & data);
Return Value

A const_buffers_1 value equivalent to:

const_buffers_1(
    data.data(),
    data.size() * sizeof(PodType));

Create a new non-modifiable buffer that represents the given POD array.

template<
    typename PodType,
    std::size_t N>
const_buffers_1 buffer(
    const std::array< PodType, N > & data,
    std::size_t max_size_in_bytes);
Return Value

A const_buffers_1 value equivalent to:

const_buffers_1(
    data.data(),
    min(data.size() * sizeof(PodType), max_size_in_bytes));

Create a new modifiable buffer that represents the given POD vector.

template<
    typename PodType,
    typename Allocator>
mutable_buffers_1 buffer(
    std::vector< PodType, Allocator > & data);
Return Value

A mutable_buffers_1 value equivalent to:

mutable_buffers_1(
    data.size() ? &data[0] : 0,
    data.size() * sizeof(PodType));
Remarks

The buffer is invalidated by any vector operation that would also invalidate iterators.

Create a new modifiable buffer that represents the given POD vector.

template<
    typename PodType,
    typename Allocator>
mutable_buffers_1 buffer(
    std::vector< PodType, Allocator > & data,
    std::size_t max_size_in_bytes);
Return Value

A mutable_buffers_1 value equivalent to:

mutable_buffers_1(
    data.size() ? &data[0] : 0,
    min(data.size() * sizeof(PodType), max_size_in_bytes));
Remarks

The buffer is invalidated by any vector operation that would also invalidate iterators.

Create a new non-modifiable buffer that represents the given POD vector.

template<
    typename PodType,
    typename Allocator>
const_buffers_1 buffer(
    const std::vector< PodType, Allocator > & data);
Return Value

A const_buffers_1 value equivalent to:

const_buffers_1(
    data.size() ? &data[0] : 0,
    data.size() * sizeof(PodType));
Remarks

The buffer is invalidated by any vector operation that would also invalidate iterators.

Create a new non-modifiable buffer that represents the given POD vector.

template<
    typename PodType,
    typename Allocator>
const_buffers_1 buffer(
    const std::vector< PodType, Allocator > & data,
    std::size_t max_size_in_bytes);
Return Value

A const_buffers_1 value equivalent to:

const_buffers_1(
    data.size() ? &data[0] : 0,
    min(data.size() * sizeof(PodType), max_size_in_bytes));
Remarks

The buffer is invalidated by any vector operation that would also invalidate iterators.

Create a new non-modifiable buffer that represents the given string.

template<
    typename Elem,
    typename Traits,
    typename Allocator>
const_buffers_1 buffer(
    const std::basic_string< Elem, Traits, Allocator > & data);
Return Value

const_buffers_1(data.data(), data.size() * sizeof(Elem)).

Remarks

The buffer is invalidated by any non-const operation called on the given string object.

Create a new non-modifiable buffer that represents the given string.

template<
    typename Elem,
    typename Traits,
    typename Allocator>
const_buffers_1 buffer(
    const std::basic_string< Elem, Traits, Allocator > & data,
    std::size_t max_size_in_bytes);
Return Value

A const_buffers_1 value equivalent to:

const_buffers_1(
    data.data(),
    min(data.size() * sizeof(Elem), max_size_in_bytes));
Remarks

The buffer is invalidated by any non-const operation called on the given string object.

The boost::asio::buffer_cast function is used to obtain a pointer to the underlying memory region associated with a buffer.

template<
    typename PointerToPodType>
PointerToPodType buffer_cast(
    const mutable_buffer & b);
  » more...

template<
    typename PointerToPodType>
PointerToPodType buffer_cast(
    const const_buffer & b);
  » more...
Examples:

To access the memory of a non-modifiable buffer, use:

boost::asio::const_buffer b1 = ...;
const unsigned char* p1 = boost::asio::buffer_cast<const unsigned char*>(b1);

To access the memory of a modifiable buffer, use:

boost::asio::mutable_buffer b2 = ...;
unsigned char* p2 = boost::asio::buffer_cast<unsigned char*>(b2);

The boost::asio::buffer_cast function permits violations of type safety, so uses of it in application code should be carefully considered.

Requirements

Header: boost/asio/buffer.hpp

Convenience header: boost/asio.hpp

Cast a non-modifiable buffer to a specified pointer to POD type.

template<
    typename PointerToPodType>
PointerToPodType buffer_cast(
    const mutable_buffer & b);

Cast a non-modifiable buffer to a specified pointer to POD type.

template<
    typename PointerToPodType>
PointerToPodType buffer_cast(
    const const_buffer & b);

The boost::asio::buffer_copy function is used to copy bytes from a source buffer (or buffer sequence) to a target buffer (or buffer sequence).

std::size_t buffer_copy(
    const mutable_buffer & target,
    const const_buffer & source);
  » more...

std::size_t buffer_copy(
    const mutable_buffer & target,
    const const_buffers_1 & source);
  » more...

std::size_t buffer_copy(
    const mutable_buffer & target,
    const mutable_buffer & source);
  » more...

std::size_t buffer_copy(
    const mutable_buffer & target,
    const mutable_buffers_1 & source);
  » more...

template<
    typename ConstBufferSequence>
std::size_t buffer_copy(
    const mutable_buffer & target,
    const ConstBufferSequence & source);
  » more...

std::size_t buffer_copy(
    const mutable_buffers_1 & target,
    const const_buffer & source);
  » more...

std::size_t buffer_copy(
    const mutable_buffers_1 & target,
    const const_buffers_1 & source);
  » more...

std::size_t buffer_copy(
    const mutable_buffers_1 & target,
    const mutable_buffer & source);
  » more...

std::size_t buffer_copy(
    const mutable_buffers_1 & target,
    const mutable_buffers_1 & source);
  » more...

template<
    typename ConstBufferSequence>
std::size_t buffer_copy(
    const mutable_buffers_1 & target,
    const ConstBufferSequence & source);
  » more...

template<
    typename MutableBufferSequence>
std::size_t buffer_copy(
    const MutableBufferSequence & target,
    const const_buffer & source);
  » more...

template<
    typename MutableBufferSequence>
std::size_t buffer_copy(
    const MutableBufferSequence & target,
    const const_buffers_1 & source);
  » more...

template<
    typename MutableBufferSequence>
std::size_t buffer_copy(
    const MutableBufferSequence & target,
    const mutable_buffer & source);
  » more...

template<
    typename MutableBufferSequence>
std::size_t buffer_copy(
    const MutableBufferSequence & target,
    const mutable_buffers_1 & source);
  » more...

template<
    typename MutableBufferSequence,
    typename ConstBufferSequence>
std::size_t buffer_copy(
    const MutableBufferSequence & target,
    const ConstBufferSequence & source);
  » more...

std::size_t buffer_copy(
    const mutable_buffer & target,
    const const_buffer & source,
    std::size_t max_bytes_to_copy);
  » more...

std::size_t buffer_copy(
    const mutable_buffer & target,
    const const_buffers_1 & source,
    std::size_t max_bytes_to_copy);
  » more...

std::size_t buffer_copy(
    const mutable_buffer & target,
    const mutable_buffer & source,
    std::size_t max_bytes_to_copy);
  » more...

std::size_t buffer_copy(
    const mutable_buffer & target,
    const mutable_buffers_1 & source,
    std::size_t max_bytes_to_copy);
  » more...

template<
    typename ConstBufferSequence>
std::size_t buffer_copy(
    const mutable_buffer & target,
    const ConstBufferSequence & source,
    std::size_t max_bytes_to_copy);
  » more...

std::size_t buffer_copy(
    const mutable_buffers_1 & target,
    const const_buffer & source,
    std::size_t max_bytes_to_copy);
  » more...

std::size_t buffer_copy(
    const mutable_buffers_1 & target,
    const const_buffers_1 & source,
    std::size_t max_bytes_to_copy);
  » more...

std::size_t buffer_copy(
    const mutable_buffers_1 & target,
    const mutable_buffer & source,
    std::size_t max_bytes_to_copy);
  » more...

std::size_t buffer_copy(
    const mutable_buffers_1 & target,
    const mutable_buffers_1 & source,
    std::size_t max_bytes_to_copy);
  » more...

template<
    typename ConstBufferSequence>
std::size_t buffer_copy(
    const mutable_buffers_1 & target,
    const ConstBufferSequence & source,
    std::size_t max_bytes_to_copy);
  » more...

template<
    typename MutableBufferSequence>
std::size_t buffer_copy(
    const MutableBufferSequence & target,
    const const_buffer & source,
    std::size_t max_bytes_to_copy);
  » more...

template<
    typename MutableBufferSequence>
std::size_t buffer_copy(
    const MutableBufferSequence & target,
    const const_buffers_1 & source,
    std::size_t max_bytes_to_copy);
  » more...

template<
    typename MutableBufferSequence>
std::size_t buffer_copy(
    const MutableBufferSequence & target,
    const mutable_buffer & source,
    std::size_t max_bytes_to_copy);
  » more...

template<
    typename MutableBufferSequence>
std::size_t buffer_copy(
    const MutableBufferSequence & target,
    const mutable_buffers_1 & source,
    std::size_t max_bytes_to_copy);
  » more...

template<
    typename MutableBufferSequence,
    typename ConstBufferSequence>
std::size_t buffer_copy(
    const MutableBufferSequence & target,
    const ConstBufferSequence & source,
    std::size_t max_bytes_to_copy);
  » more...

The buffer_copy function is available in two forms:

  • A 2-argument form: buffer_copy(target, source)
  • A 3-argument form: buffer_copy(target, source, max_bytes_to_copy)

Both forms return the number of bytes actually copied. The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)
  • If specified, max_bytes_to_copy.

This prevents buffer overflow, regardless of the buffer sizes used in the copy operation.

Note that buffer_copy is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Requirements

Header: boost/asio/buffer.hpp

Convenience header: boost/asio.hpp

Copies bytes from a source buffer to a target buffer.

std::size_t buffer_copy(
    const mutable_buffer & target,
    const const_buffer & source);
Parameters

target

A modifiable buffer representing the memory region to which the bytes will be copied.

source

A non-modifiable buffer representing the memory region from which the bytes will be copied.

Return Value

The number of bytes copied.

Remarks

The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)

This function is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Copies bytes from a source buffer to a target buffer.

std::size_t buffer_copy(
    const mutable_buffer & target,
    const const_buffers_1 & source);
Parameters

target

A modifiable buffer representing the memory region to which the bytes will be copied.

source

A non-modifiable buffer representing the memory region from which the bytes will be copied.

Return Value

The number of bytes copied.

Remarks

The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)

This function is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Copies bytes from a source buffer to a target buffer.

std::size_t buffer_copy(
    const mutable_buffer & target,
    const mutable_buffer & source);
Parameters

target

A modifiable buffer representing the memory region to which the bytes will be copied.

source

A modifiable buffer representing the memory region from which the bytes will be copied. The contents of the source buffer will not be modified.

Return Value

The number of bytes copied.

Remarks

The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)

This function is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Copies bytes from a source buffer to a target buffer.

std::size_t buffer_copy(
    const mutable_buffer & target,
    const mutable_buffers_1 & source);
Parameters

target

A modifiable buffer representing the memory region to which the bytes will be copied.

source

A modifiable buffer representing the memory region from which the bytes will be copied. The contents of the source buffer will not be modified.

Return Value

The number of bytes copied.

Remarks

The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)

This function is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Copies bytes from a source buffer sequence to a target buffer.

template<
    typename ConstBufferSequence>
std::size_t buffer_copy(
    const mutable_buffer & target,
    const ConstBufferSequence & source);
Parameters

target

A modifiable buffer representing the memory region to which the bytes will be copied.

source

A non-modifiable buffer sequence representing the memory regions from which the bytes will be copied.

Return Value

The number of bytes copied.

Remarks

The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)

This function is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Copies bytes from a source buffer to a target buffer.

std::size_t buffer_copy(
    const mutable_buffers_1 & target,
    const const_buffer & source);
Parameters

target

A modifiable buffer representing the memory region to which the bytes will be copied.

source

A non-modifiable buffer representing the memory region from which the bytes will be copied.

Return Value

The number of bytes copied.

Remarks

The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)

This function is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Copies bytes from a source buffer to a target buffer.

std::size_t buffer_copy(
    const mutable_buffers_1 & target,
    const const_buffers_1 & source);
Parameters

target

A modifiable buffer representing the memory region to which the bytes will be copied.

source

A non-modifiable buffer representing the memory region from which the bytes will be copied.

Return Value

The number of bytes copied.

Remarks

The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)

This function is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Copies bytes from a source buffer to a target buffer.

std::size_t buffer_copy(
    const mutable_buffers_1 & target,
    const mutable_buffer & source);
Parameters

target

A modifiable buffer representing the memory region to which the bytes will be copied.

source

A modifiable buffer representing the memory region from which the bytes will be copied. The contents of the source buffer will not be modified.

Return Value

The number of bytes copied.

Remarks

The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)

This function is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Copies bytes from a source buffer to a target buffer.

std::size_t buffer_copy(
    const mutable_buffers_1 & target,
    const mutable_buffers_1 & source);
Parameters

target

A modifiable buffer representing the memory region to which the bytes will be copied.

source

A modifiable buffer representing the memory region from which the bytes will be copied. The contents of the source buffer will not be modified.

Return Value

The number of bytes copied.

Remarks

The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)

This function is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Copies bytes from a source buffer sequence to a target buffer.

template<
    typename ConstBufferSequence>
std::size_t buffer_copy(
    const mutable_buffers_1 & target,
    const ConstBufferSequence & source);
Parameters

target

A modifiable buffer representing the memory region to which the bytes will be copied.

source

A non-modifiable buffer sequence representing the memory regions from which the bytes will be copied.

Return Value

The number of bytes copied.

Remarks

The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)

This function is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Copies bytes from a source buffer to a target buffer sequence.

template<
    typename MutableBufferSequence>
std::size_t buffer_copy(
    const MutableBufferSequence & target,
    const const_buffer & source);
Parameters

target

A modifiable buffer sequence representing the memory regions to which the bytes will be copied.

source

A non-modifiable buffer representing the memory region from which the bytes will be copied.

Return Value

The number of bytes copied.

Remarks

The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)

This function is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Copies bytes from a source buffer to a target buffer sequence.

template<
    typename MutableBufferSequence>
std::size_t buffer_copy(
    const MutableBufferSequence & target,
    const const_buffers_1 & source);
Parameters

target

A modifiable buffer sequence representing the memory regions to which the bytes will be copied.

source

A non-modifiable buffer representing the memory region from which the bytes will be copied.

Return Value

The number of bytes copied.

Remarks

The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)

This function is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Copies bytes from a source buffer to a target buffer sequence.

template<
    typename MutableBufferSequence>
std::size_t buffer_copy(
    const MutableBufferSequence & target,
    const mutable_buffer & source);
Parameters

target

A modifiable buffer sequence representing the memory regions to which the bytes will be copied.

source

A modifiable buffer representing the memory region from which the bytes will be copied. The contents of the source buffer will not be modified.

Return Value

The number of bytes copied.

Remarks

The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)

This function is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Copies bytes from a source buffer to a target buffer sequence.

template<
    typename MutableBufferSequence>
std::size_t buffer_copy(
    const MutableBufferSequence & target,
    const mutable_buffers_1 & source);
Parameters

target

A modifiable buffer sequence representing the memory regions to which the bytes will be copied.

source

A modifiable buffer representing the memory region from which the bytes will be copied. The contents of the source buffer will not be modified.

Return Value

The number of bytes copied.

Remarks

The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)

This function is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Copies bytes from a source buffer sequence to a target buffer sequence.

template<
    typename MutableBufferSequence,
    typename ConstBufferSequence>
std::size_t buffer_copy(
    const MutableBufferSequence & target,
    const ConstBufferSequence & source);
Parameters

target

A modifiable buffer sequence representing the memory regions to which the bytes will be copied.

source

A non-modifiable buffer sequence representing the memory regions from which the bytes will be copied.

Return Value

The number of bytes copied.

Remarks

The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)

This function is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Copies a limited number of bytes from a source buffer to a target buffer.

std::size_t buffer_copy(
    const mutable_buffer & target,
    const const_buffer & source,
    std::size_t max_bytes_to_copy);
Parameters

target

A modifiable buffer representing the memory region to which the bytes will be copied.

source

A non-modifiable buffer representing the memory region from which the bytes will be copied.

max_bytes_to_copy

The maximum number of bytes to be copied.

Return Value

The number of bytes copied.

Remarks

The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)
  • max_bytes_to_copy

This function is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Copies a limited number of bytes from a source buffer to a target buffer.

std::size_t buffer_copy(
    const mutable_buffer & target,
    const const_buffers_1 & source,
    std::size_t max_bytes_to_copy);
Parameters

target

A modifiable buffer representing the memory region to which the bytes will be copied.

source

A non-modifiable buffer representing the memory region from which the bytes will be copied.

max_bytes_to_copy

The maximum number of bytes to be copied.

Return Value

The number of bytes copied.

Remarks

The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)
  • max_bytes_to_copy

This function is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Copies a limited number of bytes from a source buffer to a target buffer.

std::size_t buffer_copy(
    const mutable_buffer & target,
    const mutable_buffer & source,
    std::size_t max_bytes_to_copy);
Parameters

target

A modifiable buffer representing the memory region to which the bytes will be copied.

source

A modifiable buffer representing the memory region from which the bytes will be copied. The contents of the source buffer will not be modified.

max_bytes_to_copy

The maximum number of bytes to be copied.

Return Value

The number of bytes copied.

Remarks

The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)
  • max_bytes_to_copy

This function is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Copies a limited number of bytes from a source buffer to a target buffer.

std::size_t buffer_copy(
    const mutable_buffer & target,
    const mutable_buffers_1 & source,
    std::size_t max_bytes_to_copy);
Parameters

target

A modifiable buffer representing the memory region to which the bytes will be copied.

source

A modifiable buffer representing the memory region from which the bytes will be copied. The contents of the source buffer will not be modified.

max_bytes_to_copy

The maximum number of bytes to be copied.

Return Value

The number of bytes copied.

Remarks

The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)
  • max_bytes_to_copy

This function is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Copies a limited number of bytes from a source buffer sequence to a target buffer.

template<
    typename ConstBufferSequence>
std::size_t buffer_copy(
    const mutable_buffer & target,
    const ConstBufferSequence & source,
    std::size_t max_bytes_to_copy);
Parameters

target

A modifiable buffer representing the memory region to which the bytes will be copied.

source

A non-modifiable buffer sequence representing the memory regions from which the bytes will be copied.

max_bytes_to_copy

The maximum number of bytes to be copied.

Return Value

The number of bytes copied.

Remarks

The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)
  • max_bytes_to_copy

This function is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Copies a limited number of bytes from a source buffer to a target buffer.

std::size_t buffer_copy(
    const mutable_buffers_1 & target,
    const const_buffer & source,
    std::size_t max_bytes_to_copy);
Parameters

target

A modifiable buffer representing the memory region to which the bytes will be copied.

source

A non-modifiable buffer representing the memory region from which the bytes will be copied.

max_bytes_to_copy

The maximum number of bytes to be copied.

Return Value

The number of bytes copied.

Remarks

The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)
  • max_bytes_to_copy

This function is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Copies a limited number of bytes from a source buffer to a target buffer.

std::size_t buffer_copy(
    const mutable_buffers_1 & target,
    const const_buffers_1 & source,
    std::size_t max_bytes_to_copy);
Parameters

target

A modifiable buffer representing the memory region to which the bytes will be copied.

source

A non-modifiable buffer representing the memory region from which the bytes will be copied.

max_bytes_to_copy

The maximum number of bytes to be copied.

Return Value

The number of bytes copied.

Remarks

The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)
  • max_bytes_to_copy

This function is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Copies a limited number of bytes from a source buffer to a target buffer.

std::size_t buffer_copy(
    const mutable_buffers_1 & target,
    const mutable_buffer & source,
    std::size_t max_bytes_to_copy);
Parameters

target

A modifiable buffer representing the memory region to which the bytes will be copied.

source

A modifiable buffer representing the memory region from which the bytes will be copied. The contents of the source buffer will not be modified.

max_bytes_to_copy

The maximum number of bytes to be copied.

Return Value

The number of bytes copied.

Remarks

The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)
  • max_bytes_to_copy

This function is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Copies a limited number of bytes from a source buffer to a target buffer.

std::size_t buffer_copy(
    const mutable_buffers_1 & target,
    const mutable_buffers_1 & source,
    std::size_t max_bytes_to_copy);
Parameters

target

A modifiable buffer representing the memory region to which the bytes will be copied.

source

A modifiable buffer representing the memory region from which the bytes will be copied. The contents of the source buffer will not be modified.

max_bytes_to_copy

The maximum number of bytes to be copied.

Return Value

The number of bytes copied.

Remarks

The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)
  • max_bytes_to_copy

This function is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Copies a limited number of bytes from a source buffer sequence to a target buffer.

template<
    typename ConstBufferSequence>
std::size_t buffer_copy(
    const mutable_buffers_1 & target,
    const ConstBufferSequence & source,
    std::size_t max_bytes_to_copy);
Parameters

target

A modifiable buffer representing the memory region to which the bytes will be copied.

source

A non-modifiable buffer sequence representing the memory regions from which the bytes will be copied.

max_bytes_to_copy

The maximum number of bytes to be copied.

Return Value

The number of bytes copied.

Remarks

The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)
  • max_bytes_to_copy

This function is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Copies a limited number of bytes from a source buffer to a target buffer sequence.

template<
    typename MutableBufferSequence>
std::size_t buffer_copy(
    const MutableBufferSequence & target,
    const const_buffer & source,
    std::size_t max_bytes_to_copy);
Parameters

target

A modifiable buffer sequence representing the memory regions to which the bytes will be copied.

source

A non-modifiable buffer representing the memory region from which the bytes will be copied.

max_bytes_to_copy

The maximum number of bytes to be copied.

Return Value

The number of bytes copied.

Remarks

The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)
  • max_bytes_to_copy

This function is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Copies a limited number of bytes from a source buffer to a target buffer sequence.

template<
    typename MutableBufferSequence>
std::size_t buffer_copy(
    const MutableBufferSequence & target,
    const const_buffers_1 & source,
    std::size_t max_bytes_to_copy);
Parameters

target

A modifiable buffer sequence representing the memory regions to which the bytes will be copied.

source

A non-modifiable buffer representing the memory region from which the bytes will be copied.

max_bytes_to_copy

The maximum number of bytes to be copied.

Return Value

The number of bytes copied.

Remarks

The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)
  • max_bytes_to_copy

This function is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Copies a limited number of bytes from a source buffer to a target buffer sequence.

template<
    typename MutableBufferSequence>
std::size_t buffer_copy(
    const MutableBufferSequence & target,
    const mutable_buffer & source,
    std::size_t max_bytes_to_copy);
Parameters

target

A modifiable buffer sequence representing the memory regions to which the bytes will be copied.

source

A modifiable buffer representing the memory region from which the bytes will be copied. The contents of the source buffer will not be modified.

max_bytes_to_copy

The maximum number of bytes to be copied.

Return Value

The number of bytes copied.

Remarks

The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)
  • max_bytes_to_copy

This function is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Copies a limited number of bytes from a source buffer to a target buffer sequence.

template<
    typename MutableBufferSequence>
std::size_t buffer_copy(
    const MutableBufferSequence & target,
    const mutable_buffers_1 & source,
    std::size_t max_bytes_to_copy);
Parameters

target

A modifiable buffer sequence representing the memory regions to which the bytes will be copied.

source

A modifiable buffer representing the memory region from which the bytes will be copied. The contents of the source buffer will not be modified.

max_bytes_to_copy

The maximum number of bytes to be copied.

Return Value

The number of bytes copied.

Remarks

The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)
  • max_bytes_to_copy

This function is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

Copies a limited number of bytes from a source buffer sequence to a target buffer sequence.

template<
    typename MutableBufferSequence,
    typename ConstBufferSequence>
std::size_t buffer_copy(
    const MutableBufferSequence & target,
    const ConstBufferSequence & source,
    std::size_t max_bytes_to_copy);
Parameters

target

A modifiable buffer sequence representing the memory regions to which the bytes will be copied.

source

A non-modifiable buffer sequence representing the memory regions from which the bytes will be copied.

max_bytes_to_copy

The maximum number of bytes to be copied.

Return Value

The number of bytes copied.

Remarks

The number of bytes copied is the lesser of:

  • buffer_size(target)
  • buffer_size(source)
  • max_bytes_to_copy

This function is implemented in terms of memcpy, and consequently it cannot be used to copy between overlapping memory regions.

The boost::asio::buffer_size function determines the total number of bytes in a buffer or buffer sequence.

std::size_t buffer_size(
    const mutable_buffer & b);
  » more...

std::size_t buffer_size(
    const mutable_buffers_1 & b);
  » more...

std::size_t buffer_size(
    const const_buffer & b);
  » more...

std::size_t buffer_size(
    const const_buffers_1 & b);
  » more...

template<
    typename BufferSequence>
std::size_t buffer_size(
    const BufferSequence & b);
  » more...
Requirements

Header: boost/asio/buffer.hpp

Convenience header: boost/asio.hpp

Get the number of bytes in a modifiable buffer.

std::size_t buffer_size(
    const mutable_buffer & b);

Get the number of bytes in a modifiable buffer.

std::size_t buffer_size(
    const mutable_buffers_1 & b);

Get the number of bytes in a non-modifiable buffer.

std::size_t buffer_size(
    const const_buffer & b);

Get the number of bytes in a non-modifiable buffer.

std::size_t buffer_size(
    const const_buffers_1 & b);

Get the total number of bytes in a buffer sequence.

template<
    typename BufferSequence>
std::size_t buffer_size(
    const BufferSequence & b);

The BufferSequence template parameter may meet either of the ConstBufferSequence or MutableBufferSequence type requirements.

Adds buffering to the read-related operations of a stream.

template<
    typename Stream>
class buffered_read_stream :
  noncopyable
Types

Name

Description

lowest_layer_type

The type of the lowest layer.

next_layer_type

The type of the next layer.

Member Functions

Name

Description

async_fill

Start an asynchronous fill.

async_read_some

Start an asynchronous read. The buffer into which the data will be read must be valid for the lifetime of the asynchronous operation.

async_write_some

Start an asynchronous write. The data being written must be valid for the lifetime of the asynchronous operation.

buffered_read_stream

Construct, passing the specified argument to initialise the next layer.

close

Close the stream.

fill

Fill the buffer with some data. Returns the number of bytes placed in the buffer as a result of the operation. Throws an exception on failure.

Fill the buffer with some data. Returns the number of bytes placed in the buffer as a result of the operation, or 0 if an error occurred.

get_io_service

Get the io_service associated with the object.

in_avail

Determine the amount of data that may be read without blocking.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

next_layer

Get a reference to the next layer.

peek

Peek at the incoming data on the stream. Returns the number of bytes read. Throws an exception on failure.

Peek at the incoming data on the stream. Returns the number of bytes read, or 0 if an error occurred.

read_some

Read some data from the stream. Returns the number of bytes read. Throws an exception on failure.

Read some data from the stream. Returns the number of bytes read or 0 if an error occurred.

write_some

Write the given data to the stream. Returns the number of bytes written. Throws an exception on failure.

Write the given data to the stream. Returns the number of bytes written, or 0 if an error occurred.

Data Members

Name

Description

default_buffer_size

The default buffer size.

The buffered_read_stream class template can be used to add buffering to the synchronous and asynchronous read operations of a stream.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/buffered_read_stream.hpp

Convenience header: boost/asio.hpp

Start an asynchronous fill.

template<
    typename ReadHandler>
void-or-deduced async_fill(
    ReadHandler handler);

Start an asynchronous read. The buffer into which the data will be read must be valid for the lifetime of the asynchronous operation.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_read_some(
    const MutableBufferSequence & buffers,
    ReadHandler handler);

Start an asynchronous write. The data being written must be valid for the lifetime of the asynchronous operation.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_write_some(
    const ConstBufferSequence & buffers,
    WriteHandler handler);

Construct, passing the specified argument to initialise the next layer.

template<
    typename Arg>
explicit buffered_read_stream(
    Arg & a);
  » more...

template<
    typename Arg>
buffered_read_stream(
    Arg & a,
    std::size_t buffer_size);
  » more...

Construct, passing the specified argument to initialise the next layer.

template<
    typename Arg>
buffered_read_stream(
    Arg & a);

Construct, passing the specified argument to initialise the next layer.

template<
    typename Arg>
buffered_read_stream(
    Arg & a,
    std::size_t buffer_size);

Close the stream.

void close();
  » more...

boost::system::error_code close(
    boost::system::error_code & ec);
  » more...

Close the stream.

void close();

Close the stream.

boost::system::error_code close(
    boost::system::error_code & ec);

The default buffer size.

static const std::size_t default_buffer_size = implementation_defined;

Fill the buffer with some data. Returns the number of bytes placed in the buffer as a result of the operation. Throws an exception on failure.

std::size_t fill();
  » more...

Fill the buffer with some data. Returns the number of bytes placed in the buffer as a result of the operation, or 0 if an error occurred.

std::size_t fill(
    boost::system::error_code & ec);
  » more...

Fill the buffer with some data. Returns the number of bytes placed in the buffer as a result of the operation. Throws an exception on failure.

std::size_t fill();

Fill the buffer with some data. Returns the number of bytes placed in the buffer as a result of the operation, or 0 if an error occurred.

std::size_t fill(
    boost::system::error_code & ec);

Get the io_service associated with the object.

boost::asio::io_service & get_io_service();

Determine the amount of data that may be read without blocking.

std::size_t in_avail();
  » more...

std::size_t in_avail(
    boost::system::error_code & ec);
  » more...

Determine the amount of data that may be read without blocking.

std::size_t in_avail();

Determine the amount of data that may be read without blocking.

std::size_t in_avail(
    boost::system::error_code & ec);

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();
  » more...

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;
  » more...

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;

The type of the lowest layer.

typedef next_layer_type::lowest_layer_type lowest_layer_type;
Requirements

Header: boost/asio/buffered_read_stream.hpp

Convenience header: boost/asio.hpp

Get a reference to the next layer.

next_layer_type & next_layer();

The type of the next layer.

typedef remove_reference< Stream >::type next_layer_type;
Requirements

Header: boost/asio/buffered_read_stream.hpp

Convenience header: boost/asio.hpp

Peek at the incoming data on the stream. Returns the number of bytes read. Throws an exception on failure.

template<
    typename MutableBufferSequence>
std::size_t peek(
    const MutableBufferSequence & buffers);
  » more...

Peek at the incoming data on the stream. Returns the number of bytes read, or 0 if an error occurred.

template<
    typename MutableBufferSequence>
std::size_t peek(
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);
  » more...

Peek at the incoming data on the stream. Returns the number of bytes read. Throws an exception on failure.

template<
    typename MutableBufferSequence>
std::size_t peek(
    const MutableBufferSequence & buffers);

Peek at the incoming data on the stream. Returns the number of bytes read, or 0 if an error occurred.

template<
    typename MutableBufferSequence>
std::size_t peek(
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);

Read some data from the stream. Returns the number of bytes read. Throws an exception on failure.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers);
  » more...

Read some data from the stream. Returns the number of bytes read or 0 if an error occurred.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);
  » more...

Read some data from the stream. Returns the number of bytes read. Throws an exception on failure.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers);

Read some data from the stream. Returns the number of bytes read or 0 if an error occurred.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);

Write the given data to the stream. Returns the number of bytes written. Throws an exception on failure.

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers);
  » more...

Write the given data to the stream. Returns the number of bytes written, or 0 if an error occurred.

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers,
    boost::system::error_code & ec);
  » more...

Write the given data to the stream. Returns the number of bytes written. Throws an exception on failure.

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers);

Write the given data to the stream. Returns the number of bytes written, or 0 if an error occurred.

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers,
    boost::system::error_code & ec);

Adds buffering to the read- and write-related operations of a stream.

template<
    typename Stream>
class buffered_stream :
  noncopyable
Types

Name

Description

lowest_layer_type

The type of the lowest layer.

next_layer_type

The type of the next layer.

Member Functions

Name

Description

async_fill

Start an asynchronous fill.

async_flush

Start an asynchronous flush.

async_read_some

Start an asynchronous read. The buffer into which the data will be read must be valid for the lifetime of the asynchronous operation.

async_write_some

Start an asynchronous write. The data being written must be valid for the lifetime of the asynchronous operation.

buffered_stream

Construct, passing the specified argument to initialise the next layer.

close

Close the stream.

fill

Fill the buffer with some data. Returns the number of bytes placed in the buffer as a result of the operation. Throws an exception on failure.

Fill the buffer with some data. Returns the number of bytes placed in the buffer as a result of the operation, or 0 if an error occurred.

flush

Flush all data from the buffer to the next layer. Returns the number of bytes written to the next layer on the last write operation. Throws an exception on failure.

Flush all data from the buffer to the next layer. Returns the number of bytes written to the next layer on the last write operation, or 0 if an error occurred.

get_io_service

Get the io_service associated with the object.

in_avail

Determine the amount of data that may be read without blocking.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

next_layer

Get a reference to the next layer.

peek

Peek at the incoming data on the stream. Returns the number of bytes read. Throws an exception on failure.

Peek at the incoming data on the stream. Returns the number of bytes read, or 0 if an error occurred.

read_some

Read some data from the stream. Returns the number of bytes read. Throws an exception on failure.

Read some data from the stream. Returns the number of bytes read or 0 if an error occurred.

write_some

Write the given data to the stream. Returns the number of bytes written. Throws an exception on failure.

Write the given data to the stream. Returns the number of bytes written, or 0 if an error occurred.

The buffered_stream class template can be used to add buffering to the synchronous and asynchronous read and write operations of a stream.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/buffered_stream.hpp

Convenience header: boost/asio.hpp

Start an asynchronous fill.

template<
    typename ReadHandler>
void-or-deduced async_fill(
    ReadHandler handler);

Start an asynchronous flush.

template<
    typename WriteHandler>
void-or-deduced async_flush(
    WriteHandler handler);

Start an asynchronous read. The buffer into which the data will be read must be valid for the lifetime of the asynchronous operation.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_read_some(
    const MutableBufferSequence & buffers,
    ReadHandler handler);

Start an asynchronous write. The data being written must be valid for the lifetime of the asynchronous operation.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_write_some(
    const ConstBufferSequence & buffers,
    WriteHandler handler);

Construct, passing the specified argument to initialise the next layer.

template<
    typename Arg>
explicit buffered_stream(
    Arg & a);
  » more...

template<
    typename Arg>
explicit buffered_stream(
    Arg & a,
    std::size_t read_buffer_size,
    std::size_t write_buffer_size);
  » more...

Construct, passing the specified argument to initialise the next layer.

template<
    typename Arg>
buffered_stream(
    Arg & a);

Construct, passing the specified argument to initialise the next layer.

template<
    typename Arg>
buffered_stream(
    Arg & a,
    std::size_t read_buffer_size,
    std::size_t write_buffer_size);

Close the stream.

void close();
  » more...

boost::system::error_code close(
    boost::system::error_code & ec);
  » more...

Close the stream.

void close();

Close the stream.

boost::system::error_code close(
    boost::system::error_code & ec);

Fill the buffer with some data. Returns the number of bytes placed in the buffer as a result of the operation. Throws an exception on failure.

std::size_t fill();
  » more...

Fill the buffer with some data. Returns the number of bytes placed in the buffer as a result of the operation, or 0 if an error occurred.

std::size_t fill(
    boost::system::error_code & ec);
  » more...

Fill the buffer with some data. Returns the number of bytes placed in the buffer as a result of the operation. Throws an exception on failure.

std::size_t fill();

Fill the buffer with some data. Returns the number of bytes placed in the buffer as a result of the operation, or 0 if an error occurred.

std::size_t fill(
    boost::system::error_code & ec);

Flush all data from the buffer to the next layer. Returns the number of bytes written to the next layer on the last write operation. Throws an exception on failure.

std::size_t flush();
  » more...

Flush all data from the buffer to the next layer. Returns the number of bytes written to the next layer on the last write operation, or 0 if an error occurred.

std::size_t flush(
    boost::system::error_code & ec);
  » more...

Flush all data from the buffer to the next layer. Returns the number of bytes written to the next layer on the last write operation. Throws an exception on failure.

std::size_t flush();

Flush all data from the buffer to the next layer. Returns the number of bytes written to the next layer on the last write operation, or 0 if an error occurred.

std::size_t flush(
    boost::system::error_code & ec);

Get the io_service associated with the object.

boost::asio::io_service & get_io_service();

Determine the amount of data that may be read without blocking.

std::size_t in_avail();
  » more...

std::size_t in_avail(
    boost::system::error_code & ec);
  » more...

Determine the amount of data that may be read without blocking.

std::size_t in_avail();

Determine the amount of data that may be read without blocking.

std::size_t in_avail(
    boost::system::error_code & ec);

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();
  » more...

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;
  » more...

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;

The type of the lowest layer.

typedef next_layer_type::lowest_layer_type lowest_layer_type;
Requirements

Header: boost/asio/buffered_stream.hpp

Convenience header: boost/asio.hpp

Get a reference to the next layer.

next_layer_type & next_layer();

The type of the next layer.

typedef remove_reference< Stream >::type next_layer_type;
Requirements

Header: boost/asio/buffered_stream.hpp

Convenience header: boost/asio.hpp

Peek at the incoming data on the stream. Returns the number of bytes read. Throws an exception on failure.

template<
    typename MutableBufferSequence>
std::size_t peek(
    const MutableBufferSequence & buffers);
  » more...

Peek at the incoming data on the stream. Returns the number of bytes read, or 0 if an error occurred.

template<
    typename MutableBufferSequence>
std::size_t peek(
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);
  » more...

Peek at the incoming data on the stream. Returns the number of bytes read. Throws an exception on failure.

template<
    typename MutableBufferSequence>
std::size_t peek(
    const MutableBufferSequence & buffers);

Peek at the incoming data on the stream. Returns the number of bytes read, or 0 if an error occurred.

template<
    typename MutableBufferSequence>
std::size_t peek(
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);

Read some data from the stream. Returns the number of bytes read. Throws an exception on failure.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers);
  » more...

Read some data from the stream. Returns the number of bytes read or 0 if an error occurred.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);
  » more...

Read some data from the stream. Returns the number of bytes read. Throws an exception on failure.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers);

Read some data from the stream. Returns the number of bytes read or 0 if an error occurred.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);

Write the given data to the stream. Returns the number of bytes written. Throws an exception on failure.

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers);
  » more...

Write the given data to the stream. Returns the number of bytes written, or 0 if an error occurred.

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers,
    boost::system::error_code & ec);
  » more...

Write the given data to the stream. Returns the number of bytes written. Throws an exception on failure.

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers);

Write the given data to the stream. Returns the number of bytes written, or 0 if an error occurred.

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers,
    boost::system::error_code & ec);

Adds buffering to the write-related operations of a stream.

template<
    typename Stream>
class buffered_write_stream :
  noncopyable
Types

Name

Description

lowest_layer_type

The type of the lowest layer.

next_layer_type

The type of the next layer.

Member Functions

Name

Description

async_flush

Start an asynchronous flush.

async_read_some

Start an asynchronous read. The buffer into which the data will be read must be valid for the lifetime of the asynchronous operation.

async_write_some

Start an asynchronous write. The data being written must be valid for the lifetime of the asynchronous operation.

buffered_write_stream

Construct, passing the specified argument to initialise the next layer.

close

Close the stream.

flush

Flush all data from the buffer to the next layer. Returns the number of bytes written to the next layer on the last write operation. Throws an exception on failure.

Flush all data from the buffer to the next layer. Returns the number of bytes written to the next layer on the last write operation, or 0 if an error occurred.

get_io_service

Get the io_service associated with the object.

in_avail

Determine the amount of data that may be read without blocking.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

next_layer

Get a reference to the next layer.

peek

Peek at the incoming data on the stream. Returns the number of bytes read. Throws an exception on failure.

Peek at the incoming data on the stream. Returns the number of bytes read, or 0 if an error occurred.

read_some

Read some data from the stream. Returns the number of bytes read. Throws an exception on failure.

Read some data from the stream. Returns the number of bytes read or 0 if an error occurred.

write_some

Write the given data to the stream. Returns the number of bytes written. Throws an exception on failure.

Write the given data to the stream. Returns the number of bytes written, or 0 if an error occurred and the error handler did not throw.

Data Members

Name

Description

default_buffer_size

The default buffer size.

The buffered_write_stream class template can be used to add buffering to the synchronous and asynchronous write operations of a stream.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/buffered_write_stream.hpp

Convenience header: boost/asio.hpp

Start an asynchronous flush.

template<
    typename WriteHandler>
void-or-deduced async_flush(
    WriteHandler handler);

Start an asynchronous read. The buffer into which the data will be read must be valid for the lifetime of the asynchronous operation.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_read_some(
    const MutableBufferSequence & buffers,
    ReadHandler handler);

Start an asynchronous write. The data being written must be valid for the lifetime of the asynchronous operation.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_write_some(
    const ConstBufferSequence & buffers,
    WriteHandler handler);

Construct, passing the specified argument to initialise the next layer.

template<
    typename Arg>
explicit buffered_write_stream(
    Arg & a);
  » more...

template<
    typename Arg>
buffered_write_stream(
    Arg & a,
    std::size_t buffer_size);
  » more...

Construct, passing the specified argument to initialise the next layer.

template<
    typename Arg>
buffered_write_stream(
    Arg & a);

Construct, passing the specified argument to initialise the next layer.

template<
    typename Arg>
buffered_write_stream(
    Arg & a,
    std::size_t buffer_size);

Close the stream.

void close();
  » more...

boost::system::error_code close(
    boost::system::error_code & ec);
  » more...

Close the stream.

void close();

Close the stream.

boost::system::error_code close(
    boost::system::error_code & ec);

The default buffer size.

static const std::size_t default_buffer_size = implementation_defined;

Flush all data from the buffer to the next layer. Returns the number of bytes written to the next layer on the last write operation. Throws an exception on failure.

std::size_t flush();
  » more...

Flush all data from the buffer to the next layer. Returns the number of bytes written to the next layer on the last write operation, or 0 if an error occurred.

std::size_t flush(
    boost::system::error_code & ec);
  » more...

Flush all data from the buffer to the next layer. Returns the number of bytes written to the next layer on the last write operation. Throws an exception on failure.

std::size_t flush();

Flush all data from the buffer to the next layer. Returns the number of bytes written to the next layer on the last write operation, or 0 if an error occurred.

std::size_t flush(
    boost::system::error_code & ec);

Get the io_service associated with the object.

boost::asio::io_service & get_io_service();

Determine the amount of data that may be read without blocking.

std::size_t in_avail();
  » more...

std::size_t in_avail(
    boost::system::error_code & ec);
  » more...

Determine the amount of data that may be read without blocking.

std::size_t in_avail();

Determine the amount of data that may be read without blocking.

std::size_t in_avail(
    boost::system::error_code & ec);

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();
  » more...

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;
  » more...

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;

The type of the lowest layer.

typedef next_layer_type::lowest_layer_type lowest_layer_type;
Requirements

Header: boost/asio/buffered_write_stream.hpp

Convenience header: boost/asio.hpp

Get a reference to the next layer.

next_layer_type & next_layer();

The type of the next layer.

typedef remove_reference< Stream >::type next_layer_type;
Requirements

Header: boost/asio/buffered_write_stream.hpp

Convenience header: boost/asio.hpp

Peek at the incoming data on the stream. Returns the number of bytes read. Throws an exception on failure.

template<
    typename MutableBufferSequence>
std::size_t peek(
    const MutableBufferSequence & buffers);
  » more...

Peek at the incoming data on the stream. Returns the number of bytes read, or 0 if an error occurred.

template<
    typename MutableBufferSequence>
std::size_t peek(
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);
  » more...

Peek at the incoming data on the stream. Returns the number of bytes read. Throws an exception on failure.

template<
    typename MutableBufferSequence>
std::size_t peek(
    const MutableBufferSequence & buffers);

Peek at the incoming data on the stream. Returns the number of bytes read, or 0 if an error occurred.

template<
    typename MutableBufferSequence>
std::size_t peek(
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);

Read some data from the stream. Returns the number of bytes read. Throws an exception on failure.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers);
  » more...

Read some data from the stream. Returns the number of bytes read or 0 if an error occurred.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);
  » more...

Read some data from the stream. Returns the number of bytes read. Throws an exception on failure.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers);

Read some data from the stream. Returns the number of bytes read or 0 if an error occurred.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);

Write the given data to the stream. Returns the number of bytes written. Throws an exception on failure.

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers);
  » more...

Write the given data to the stream. Returns the number of bytes written, or 0 if an error occurred and the error handler did not throw.

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers,
    boost::system::error_code & ec);
  » more...

Write the given data to the stream. Returns the number of bytes written. Throws an exception on failure.

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers);

Write the given data to the stream. Returns the number of bytes written, or 0 if an error occurred and the error handler did not throw.

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers,
    boost::system::error_code & ec);

Construct an iterator representing the beginning of the buffers' data.

template<
    typename BufferSequence>
buffers_iterator< BufferSequence > buffers_begin(
    const BufferSequence & buffers);
Requirements

Header: boost/asio/buffers_iterator.hpp

Convenience header: boost/asio.hpp

Construct an iterator representing the end of the buffers' data.

template<
    typename BufferSequence>
buffers_iterator< BufferSequence > buffers_end(
    const BufferSequence & buffers);
Requirements

Header: boost/asio/buffers_iterator.hpp

Convenience header: boost/asio.hpp

A random access iterator over the bytes in a buffer sequence.

template<
    typename BufferSequence,
    typename ByteType = char>
class buffers_iterator
Types

Name

Description

difference_type

The type used for the distance between two iterators.

iterator_category

The iterator category.

pointer

The type of the result of applying operator->() to the iterator.

reference

The type of the result of applying operator*() to the iterator.

value_type

The type of the value pointed to by the iterator.

Member Functions

Name

Description

begin

Construct an iterator representing the beginning of the buffers' data.

buffers_iterator

Default constructor. Creates an iterator in an undefined state.

end

Construct an iterator representing the end of the buffers' data.

operator *

Dereference an iterator.

operator++

Increment operator (prefix).

Increment operator (postfix).

operator+=

Addition operator.

operator--

Decrement operator (prefix).

Decrement operator (postfix).

operator-=

Subtraction operator.

operator->

Dereference an iterator.

operator[]

Access an individual element.

Friends

Name

Description

operator!=

Test two iterators for inequality.

operator+

Addition operator.

operator-

Subtraction operator.

operator<

Compare two iterators.

operator<=

Compare two iterators.

operator==

Test two iterators for equality.

operator>

Compare two iterators.

operator>=

Compare two iterators.

Requirements

Header: boost/asio/buffers_iterator.hpp

Convenience header: boost/asio.hpp

Construct an iterator representing the beginning of the buffers' data.

static buffers_iterator begin(
    const BufferSequence & buffers);

Default constructor. Creates an iterator in an undefined state.

buffers_iterator();

The type used for the distance between two iterators.

typedef std::ptrdiff_t difference_type;
Requirements

Header: boost/asio/buffers_iterator.hpp

Convenience header: boost/asio.hpp

Construct an iterator representing the end of the buffers' data.

static buffers_iterator end(
    const BufferSequence & buffers);

The iterator category.

typedef std::random_access_iterator_tag iterator_category;
Requirements

Header: boost/asio/buffers_iterator.hpp

Convenience header: boost/asio.hpp

Dereference an iterator.

reference operator *() const;

Test two iterators for inequality.

friend bool operator!=(
    const buffers_iterator & a,
    const buffers_iterator & b);
Requirements

Header: boost/asio/buffers_iterator.hpp

Convenience header: boost/asio.hpp

Addition operator.

friend buffers_iterator operator+(
    const buffers_iterator & iter,
    std::ptrdiff_t difference);
  » more...

friend buffers_iterator operator+(
    std::ptrdiff_t difference,
    const buffers_iterator & iter);
  » more...

Addition operator.

friend buffers_iterator operator+(
    const buffers_iterator & iter,
    std::ptrdiff_t difference);
Requirements

Header: boost/asio/buffers_iterator.hpp

Convenience header: boost/asio.hpp

Addition operator.

friend buffers_iterator operator+(
    std::ptrdiff_t difference,
    const buffers_iterator & iter);
Requirements

Header: boost/asio/buffers_iterator.hpp

Convenience header: boost/asio.hpp

Increment operator (prefix).

buffers_iterator & operator++();
  » more...

Increment operator (postfix).

buffers_iterator operator++(
    int );
  » more...

Increment operator (prefix).

buffers_iterator & operator++();

Increment operator (postfix).

buffers_iterator operator++(
    int );

Addition operator.

buffers_iterator & operator+=(
    std::ptrdiff_t difference);

Subtraction operator.

friend buffers_iterator operator-(
    const buffers_iterator & iter,
    std::ptrdiff_t difference);
  » more...

friend std::ptrdiff_t operator-(
    const buffers_iterator & a,
    const buffers_iterator & b);
  » more...

Subtraction operator.

friend buffers_iterator operator-(
    const buffers_iterator & iter,
    std::ptrdiff_t difference);
Requirements

Header: boost/asio/buffers_iterator.hpp

Convenience header: boost/asio.hpp

Subtraction operator.

friend std::ptrdiff_t operator-(
    const buffers_iterator & a,
    const buffers_iterator & b);
Requirements

Header: boost/asio/buffers_iterator.hpp

Convenience header: boost/asio.hpp

Decrement operator (prefix).

buffers_iterator & operator--();
  » more...

Decrement operator (postfix).

buffers_iterator operator--(
    int );
  » more...

Decrement operator (prefix).

buffers_iterator & operator--();

Decrement operator (postfix).

buffers_iterator operator--(
    int );

Subtraction operator.

buffers_iterator & operator-=(
    std::ptrdiff_t difference);

Dereference an iterator.

pointer operator->() const;

Compare two iterators.

friend bool operator<(
    const buffers_iterator & a,
    const buffers_iterator & b);
Requirements

Header: boost/asio/buffers_iterator.hpp

Convenience header: boost/asio.hpp

Compare two iterators.

friend bool operator<=(
    const buffers_iterator & a,
    const buffers_iterator & b);
Requirements

Header: boost/asio/buffers_iterator.hpp

Convenience header: boost/asio.hpp

Test two iterators for equality.

friend bool operator==(
    const buffers_iterator & a,
    const buffers_iterator & b);
Requirements

Header: boost/asio/buffers_iterator.hpp

Convenience header: boost/asio.hpp

Compare two iterators.

friend bool operator>(
    const buffers_iterator & a,
    const buffers_iterator & b);
Requirements

Header: boost/asio/buffers_iterator.hpp

Convenience header: boost/asio.hpp

Compare two iterators.

friend bool operator>=(
    const buffers_iterator & a,
    const buffers_iterator & b);
Requirements

Header: boost/asio/buffers_iterator.hpp

Convenience header: boost/asio.hpp

Access an individual element.

reference operator[](
    std::ptrdiff_t difference) const;

The type of the result of applying operator->() to the iterator.

typedef const_or_non_const_ByteType * pointer;

If the buffer sequence stores buffer objects that are convertible to mutable_buffer, this is a pointer to a non-const ByteType. Otherwise, a pointer to a const ByteType.

Requirements

Header: boost/asio/buffers_iterator.hpp

Convenience header: boost/asio.hpp

The type of the result of applying operator*() to the iterator.

typedef const_or_non_const_ByteType & reference;

If the buffer sequence stores buffer objects that are convertible to mutable_buffer, this is a reference to a non-const ByteType. Otherwise, a reference to a const ByteType.

Requirements

Header: boost/asio/buffers_iterator.hpp

Convenience header: boost/asio.hpp

The type of the value pointed to by the iterator.

typedef ByteType value_type;
Requirements

Header: boost/asio/buffers_iterator.hpp

Convenience header: boost/asio.hpp

Establishes a socket connection by trying each endpoint in a sequence.

template<
    typename Protocol,
    typename SocketService,
    typename Iterator>
Iterator connect(
    basic_socket< Protocol, SocketService > & s,
    Iterator begin);
  » more...

template<
    typename Protocol,
    typename SocketService,
    typename Iterator>
Iterator connect(
    basic_socket< Protocol, SocketService > & s,
    Iterator begin,
    boost::system::error_code & ec);
  » more...

template<
    typename Protocol,
    typename SocketService,
    typename Iterator>
Iterator connect(
    basic_socket< Protocol, SocketService > & s,
    Iterator begin,
    Iterator end);
  » more...

template<
    typename Protocol,
    typename SocketService,
    typename Iterator>
Iterator connect(
    basic_socket< Protocol, SocketService > & s,
    Iterator begin,
    Iterator end,
    boost::system::error_code & ec);
  » more...

template<
    typename Protocol,
    typename SocketService,
    typename Iterator,
    typename ConnectCondition>
Iterator connect(
    basic_socket< Protocol, SocketService > & s,
    Iterator begin,
    ConnectCondition connect_condition);
  » more...

template<
    typename Protocol,
    typename SocketService,
    typename Iterator,
    typename ConnectCondition>
Iterator connect(
    basic_socket< Protocol, SocketService > & s,
    Iterator begin,
    ConnectCondition connect_condition,
    boost::system::error_code & ec);
  » more...

template<
    typename Protocol,
    typename SocketService,
    typename Iterator,
    typename ConnectCondition>
Iterator connect(
    basic_socket< Protocol, SocketService > & s,
    Iterator begin,
    Iterator end,
    ConnectCondition connect_condition);
  » more...

template<
    typename Protocol,
    typename SocketService,
    typename Iterator,
    typename ConnectCondition>
Iterator connect(
    basic_socket< Protocol, SocketService > & s,
    Iterator begin,
    Iterator end,
    ConnectCondition connect_condition,
    boost::system::error_code & ec);
  » more...
Requirements

Header: boost/asio/connect.hpp

Convenience header: boost/asio.hpp

Establishes a socket connection by trying each endpoint in a sequence.

template<
    typename Protocol,
    typename SocketService,
    typename Iterator>
Iterator connect(
    basic_socket< Protocol, SocketService > & s,
    Iterator begin);

This function attempts to connect a socket to one of a sequence of endpoints. It does this by repeated calls to the socket's connect member function, once for each endpoint in the sequence, until a connection is successfully established.

Parameters

s

The socket to be connected. If the socket is already open, it will be closed.

begin

An iterator pointing to the start of a sequence of endpoints.

Return Value

On success, an iterator denoting the successfully connected endpoint. Otherwise, the end iterator.

Exceptions

boost::system::system_error

Thrown on failure. If the sequence is empty, the associated error_code is boost::asio::error::not_found. Otherwise, contains the error from the last connection attempt.

Remarks

This overload assumes that a default constructed object of type Iterator represents the end of the sequence. This is a valid assumption for iterator types such as boost::asio::ip::tcp::resolver::iterator.

Example
tcp::resolver r(io_service);
tcp::resolver::query q("host", "service");
tcp::socket s(io_service);
boost::asio::connect(s, r.resolve(q));

Establishes a socket connection by trying each endpoint in a sequence.

template<
    typename Protocol,
    typename SocketService,
    typename Iterator>
Iterator connect(
    basic_socket< Protocol, SocketService > & s,
    Iterator begin,
    boost::system::error_code & ec);

This function attempts to connect a socket to one of a sequence of endpoints. It does this by repeated calls to the socket's connect member function, once for each endpoint in the sequence, until a connection is successfully established.

Parameters

s

The socket to be connected. If the socket is already open, it will be closed.

begin

An iterator pointing to the start of a sequence of endpoints.

ec

Set to indicate what error occurred, if any. If the sequence is empty, set to boost::asio::error::not_found. Otherwise, contains the error from the last connection attempt.

Return Value

On success, an iterator denoting the successfully connected endpoint. Otherwise, the end iterator.

Remarks

This overload assumes that a default constructed object of type Iterator represents the end of the sequence. This is a valid assumption for iterator types such as boost::asio::ip::tcp::resolver::iterator.

Example
tcp::resolver r(io_service);
tcp::resolver::query q("host", "service");
tcp::socket s(io_service);
boost::system::error_code ec;
boost::asio::connect(s, r.resolve(q), ec);
if (ec)
{
  // An error occurred.
}

Establishes a socket connection by trying each endpoint in a sequence.

template<
    typename Protocol,
    typename SocketService,
    typename Iterator>
Iterator connect(
    basic_socket< Protocol, SocketService > & s,
    Iterator begin,
    Iterator end);

This function attempts to connect a socket to one of a sequence of endpoints. It does this by repeated calls to the socket's connect member function, once for each endpoint in the sequence, until a connection is successfully established.

Parameters

s

The socket to be connected. If the socket is already open, it will be closed.

begin

An iterator pointing to the start of a sequence of endpoints.

end

An iterator pointing to the end of a sequence of endpoints.

Return Value

On success, an iterator denoting the successfully connected endpoint. Otherwise, the end iterator.

Exceptions

boost::system::system_error

Thrown on failure. If the sequence is empty, the associated error_code is boost::asio::error::not_found. Otherwise, contains the error from the last connection attempt.

Example
tcp::resolver r(io_service);
tcp::resolver::query q("host", "service");
tcp::resolver::iterator i = r.resolve(q), end;
tcp::socket s(io_service);
boost::asio::connect(s, i, end);

Establishes a socket connection by trying each endpoint in a sequence.

template<
    typename Protocol,
    typename SocketService,
    typename Iterator>
Iterator connect(
    basic_socket< Protocol, SocketService > & s,
    Iterator begin,
    Iterator end,
    boost::system::error_code & ec);

This function attempts to connect a socket to one of a sequence of endpoints. It does this by repeated calls to the socket's connect member function, once for each endpoint in the sequence, until a connection is successfully established.

Parameters

s

The socket to be connected. If the socket is already open, it will be closed.

begin

An iterator pointing to the start of a sequence of endpoints.

end

An iterator pointing to the end of a sequence of endpoints.

ec

Set to indicate what error occurred, if any. If the sequence is empty, set to boost::asio::error::not_found. Otherwise, contains the error from the last connection attempt.

Return Value

On success, an iterator denoting the successfully connected endpoint. Otherwise, the end iterator.

Example
tcp::resolver r(io_service);
tcp::resolver::query q("host", "service");
tcp::resolver::iterator i = r.resolve(q), end;
tcp::socket s(io_service);
boost::system::error_code ec;
boost::asio::connect(s, i, end, ec);
if (ec)
{
  // An error occurred.
}

Establishes a socket connection by trying each endpoint in a sequence.

template<
    typename Protocol,
    typename SocketService,
    typename Iterator,
    typename ConnectCondition>
Iterator connect(
    basic_socket< Protocol, SocketService > & s,
    Iterator begin,
    ConnectCondition connect_condition);

This function attempts to connect a socket to one of a sequence of endpoints. It does this by repeated calls to the socket's connect member function, once for each endpoint in the sequence, until a connection is successfully established.

Parameters

s

The socket to be connected. If the socket is already open, it will be closed.

begin

An iterator pointing to the start of a sequence of endpoints.

connect_condition

A function object that is called prior to each connection attempt. The signature of the function object must be:

Iterator connect_condition(
    const boost::system::error_code& ec,
    Iterator next);

The ec parameter contains the result from the most recent connect operation. Before the first connection attempt, ec is always set to indicate success. The next parameter is an iterator pointing to the next endpoint to be tried. The function object should return the next iterator, but is permitted to return a different iterator so that endpoints may be skipped. The implementation guarantees that the function object will never be called with the end iterator.

Return Value

On success, an iterator denoting the successfully connected endpoint. Otherwise, the end iterator.

Exceptions

boost::system::system_error

Thrown on failure. If the sequence is empty, the associated error_code is boost::asio::error::not_found. Otherwise, contains the error from the last connection attempt.

Remarks

This overload assumes that a default constructed object of type Iterator represents the end of the sequence. This is a valid assumption for iterator types such as boost::asio::ip::tcp::resolver::iterator.

Example

The following connect condition function object can be used to output information about the individual connection attempts:

struct my_connect_condition
{
  template <typename Iterator>
  Iterator operator()(
      const boost::system::error_code& ec,
      Iterator next)
  {
    if (ec) std::cout << "Error: " << ec.message() << std::endl;
    std::cout << "Trying: " << next->endpoint() << std::endl;
    return next;
  }
};

It would be used with the boost::asio::connect function as follows:

tcp::resolver r(io_service);
tcp::resolver::query q("host", "service");
tcp::socket s(io_service);
tcp::resolver::iterator i = boost::asio::connect(
    s, r.resolve(q), my_connect_condition());
std::cout << "Connected to: " << i->endpoint() << std::endl;

Establishes a socket connection by trying each endpoint in a sequence.

template<
    typename Protocol,
    typename SocketService,
    typename Iterator,
    typename ConnectCondition>
Iterator connect(
    basic_socket< Protocol, SocketService > & s,
    Iterator begin,
    ConnectCondition connect_condition,
    boost::system::error_code & ec);

This function attempts to connect a socket to one of a sequence of endpoints. It does this by repeated calls to the socket's connect member function, once for each endpoint in the sequence, until a connection is successfully established.

Parameters

s

The socket to be connected. If the socket is already open, it will be closed.

begin

An iterator pointing to the start of a sequence of endpoints.

connect_condition

A function object that is called prior to each connection attempt. The signature of the function object must be:

Iterator connect_condition(
    const boost::system::error_code& ec,
    Iterator next);

The ec parameter contains the result from the most recent connect operation. Before the first connection attempt, ec is always set to indicate success. The next parameter is an iterator pointing to the next endpoint to be tried. The function object should return the next iterator, but is permitted to return a different iterator so that endpoints may be skipped. The implementation guarantees that the function object will never be called with the end iterator.

ec

Set to indicate what error occurred, if any. If the sequence is empty, set to boost::asio::error::not_found. Otherwise, contains the error from the last connection attempt.

Return Value

On success, an iterator denoting the successfully connected endpoint. Otherwise, the end iterator.

Remarks

This overload assumes that a default constructed object of type Iterator represents the end of the sequence. This is a valid assumption for iterator types such as boost::asio::ip::tcp::resolver::iterator.

Example

The following connect condition function object can be used to output information about the individual connection attempts:

struct my_connect_condition
{
  template <typename Iterator>
  Iterator operator()(
      const boost::system::error_code& ec,
      Iterator next)
  {
    if (ec) std::cout << "Error: " << ec.message() << std::endl;
    std::cout << "Trying: " << next->endpoint() << std::endl;
    return next;
  }
};

It would be used with the boost::asio::connect function as follows:

tcp::resolver r(io_service);
tcp::resolver::query q("host", "service");
tcp::socket s(io_service);
boost::system::error_code ec;
tcp::resolver::iterator i = boost::asio::connect(
    s, r.resolve(q), my_connect_condition(), ec);
if (ec)
{
  // An error occurred.
}
else
{
  std::cout << "Connected to: " << i->endpoint() << std::endl;
}

Establishes a socket connection by trying each endpoint in a sequence.

template<
    typename Protocol,
    typename SocketService,
    typename Iterator,
    typename ConnectCondition>
Iterator connect(
    basic_socket< Protocol, SocketService > & s,
    Iterator begin,
    Iterator end,
    ConnectCondition connect_condition);

This function attempts to connect a socket to one of a sequence of endpoints. It does this by repeated calls to the socket's connect member function, once for each endpoint in the sequence, until a connection is successfully established.

Parameters

s

The socket to be connected. If the socket is already open, it will be closed.

begin

An iterator pointing to the start of a sequence of endpoints.

end

An iterator pointing to the end of a sequence of endpoints.

connect_condition

A function object that is called prior to each connection attempt. The signature of the function object must be:

Iterator connect_condition(
    const boost::system::error_code& ec,
    Iterator next);

The ec parameter contains the result from the most recent connect operation. Before the first connection attempt, ec is always set to indicate success. The next parameter is an iterator pointing to the next endpoint to be tried. The function object should return the next iterator, but is permitted to return a different iterator so that endpoints may be skipped. The implementation guarantees that the function object will never be called with the end iterator.

Return Value

On success, an iterator denoting the successfully connected endpoint. Otherwise, the end iterator.

Exceptions

boost::system::system_error

Thrown on failure. If the sequence is empty, the associated error_code is boost::asio::error::not_found. Otherwise, contains the error from the last connection attempt.

Example

The following connect condition function object can be used to output information about the individual connection attempts:

struct my_connect_condition
{
  template <typename Iterator>
  Iterator operator()(
      const boost::system::error_code& ec,
      Iterator next)
  {
    if (ec) std::cout << "Error: " << ec.message() << std::endl;
    std::cout << "Trying: " << next->endpoint() << std::endl;
    return next;
  }
};

It would be used with the boost::asio::connect function as follows:

tcp::resolver r(io_service);
tcp::resolver::query q("host", "service");
tcp::resolver::iterator i = r.resolve(q), end;
tcp::socket s(io_service);
i = boost::asio::connect(s, i, end, my_connect_condition());
std::cout << "Connected to: " << i->endpoint() << std::endl;

Establishes a socket connection by trying each endpoint in a sequence.

template<
    typename Protocol,
    typename SocketService,
    typename Iterator,
    typename ConnectCondition>
Iterator connect(
    basic_socket< Protocol, SocketService > & s,
    Iterator begin,
    Iterator end,
    ConnectCondition connect_condition,
    boost::system::error_code & ec);

This function attempts to connect a socket to one of a sequence of endpoints. It does this by repeated calls to the socket's connect member function, once for each endpoint in the sequence, until a connection is successfully established.

Parameters

s

The socket to be connected. If the socket is already open, it will be closed.

begin

An iterator pointing to the start of a sequence of endpoints.

end

An iterator pointing to the end of a sequence of endpoints.

connect_condition

A function object that is called prior to each connection attempt. The signature of the function object must be:

Iterator connect_condition(
    const boost::system::error_code& ec,
    Iterator next);

The ec parameter contains the result from the most recent connect operation. Before the first connection attempt, ec is always set to indicate success. The next parameter is an iterator pointing to the next endpoint to be tried. The function object should return the next iterator, but is permitted to return a different iterator so that endpoints may be skipped. The implementation guarantees that the function object will never be called with the end iterator.

ec

Set to indicate what error occurred, if any. If the sequence is empty, set to boost::asio::error::not_found. Otherwise, contains the error from the last connection attempt.

Return Value

On success, an iterator denoting the successfully connected endpoint. Otherwise, the end iterator.

Example

The following connect condition function object can be used to output information about the individual connection attempts:

struct my_connect_condition
{
  template <typename Iterator>
  Iterator operator()(
      const boost::system::error_code& ec,
      Iterator next)
  {
    if (ec) std::cout << "Error: " << ec.message() << std::endl;
    std::cout << "Trying: " << next->endpoint() << std::endl;
    return next;
  }
};

It would be used with the boost::asio::connect function as follows:

tcp::resolver r(io_service);
tcp::resolver::query q("host", "service");
tcp::resolver::iterator i = r.resolve(q), end;
tcp::socket s(io_service);
boost::system::error_code ec;
i = boost::asio::connect(s, i, end, my_connect_condition(), ec);
if (ec)
{
  // An error occurred.
}
else
{
  std::cout << "Connected to: " << i->endpoint() << std::endl;
}

Holds a buffer that cannot be modified.

class const_buffer
Member Functions

Name

Description

const_buffer

Construct an empty buffer.

Construct a buffer to represent a given memory range.

Construct a non-modifiable buffer from a modifiable one.

Related Functions

Name

Description

operator+

Create a new non-modifiable buffer that is offset from the start of another.

The const_buffer class provides a safe representation of a buffer that cannot be modified. It does not own the underlying data, and so is cheap to copy or assign.

Accessing Buffer Contents

The contents of a buffer may be accessed using the buffer_size and buffer_cast functions:

boost::asio::const_buffer b1 = ...;
std::size_t s1 = boost::asio::buffer_size(b1);
const unsigned char* p1 = boost::asio::buffer_cast<const unsigned char*>(b1);

The boost::asio::buffer_cast function permits violations of type safety, so uses of it in application code should be carefully considered.

Requirements

Header: boost/asio/buffer.hpp

Convenience header: boost/asio.hpp

Construct an empty buffer.

const_buffer();
  » more...

Construct a buffer to represent a given memory range.

const_buffer(
    const void * data,
    std::size_t size);
  » more...

Construct a non-modifiable buffer from a modifiable one.

const_buffer(
    const mutable_buffer & b);
  » more...

Construct an empty buffer.

const_buffer();

Construct a buffer to represent a given memory range.

const_buffer(
    const void * data,
    std::size_t size);

Construct a non-modifiable buffer from a modifiable one.

const_buffer(
    const mutable_buffer & b);

Create a new non-modifiable buffer that is offset from the start of another.

const_buffer operator+(
    const const_buffer & b,
    std::size_t start);
  » more...

const_buffer operator+(
    std::size_t start,
    const const_buffer & b);
  » more...

Create a new non-modifiable buffer that is offset from the start of another.

const_buffer operator+(
    const const_buffer & b,
    std::size_t start);

Create a new non-modifiable buffer that is offset from the start of another.

const_buffer operator+(
    std::size_t start,
    const const_buffer & b);

Adapts a single non-modifiable buffer so that it meets the requirements of the ConstBufferSequence concept.

class const_buffers_1 :
  public const_buffer
Types

Name

Description

const_iterator

A random-access iterator type that may be used to read elements.

value_type

The type for each element in the list of buffers.

Member Functions

Name

Description

begin

Get a random-access iterator to the first element.

const_buffers_1

Construct to represent a given memory range.

Construct to represent a single non-modifiable buffer.

end

Get a random-access iterator for one past the last element.

Related Functions

Name

Description

operator+

Create a new non-modifiable buffer that is offset from the start of another.

Requirements

Header: boost/asio/buffer.hpp

Convenience header: boost/asio.hpp

Get a random-access iterator to the first element.

const_iterator begin() const;

Construct to represent a given memory range.

const_buffers_1(
    const void * data,
    std::size_t size);
  » more...

Construct to represent a single non-modifiable buffer.

explicit const_buffers_1(
    const const_buffer & b);
  » more...

Construct to represent a given memory range.

const_buffers_1(
    const void * data,
    std::size_t size);

Construct to represent a single non-modifiable buffer.

const_buffers_1(
    const const_buffer & b);

A random-access iterator type that may be used to read elements.

typedef const const_buffer * const_iterator;
Requirements

Header: boost/asio/buffer.hpp

Convenience header: boost/asio.hpp

Get a random-access iterator for one past the last element.

const_iterator end() const;

Create a new non-modifiable buffer that is offset from the start of another.

const_buffer operator+(
    const const_buffer & b,
    std::size_t start);
  » more...

const_buffer operator+(
    std::size_t start,
    const const_buffer & b);
  » more...

Inherited from const_buffer.

Create a new non-modifiable buffer that is offset from the start of another.

const_buffer operator+(
    const const_buffer & b,
    std::size_t start);

Inherited from const_buffer.

Create a new non-modifiable buffer that is offset from the start of another.

const_buffer operator+(
    std::size_t start,
    const const_buffer & b);

The type for each element in the list of buffers.

typedef const_buffer value_type;
Member Functions

Name

Description

const_buffer

Construct an empty buffer.

Construct a buffer to represent a given memory range.

Construct a non-modifiable buffer from a modifiable one.

Related Functions

Name

Description

operator+

Create a new non-modifiable buffer that is offset from the start of another.

The const_buffer class provides a safe representation of a buffer that cannot be modified. It does not own the underlying data, and so is cheap to copy or assign.

Accessing Buffer Contents

The contents of a buffer may be accessed using the buffer_size and buffer_cast functions:

boost::asio::const_buffer b1 = ...;
std::size_t s1 = boost::asio::buffer_size(b1);
const unsigned char* p1 = boost::asio::buffer_cast<const unsigned char*>(b1);

The boost::asio::buffer_cast function permits violations of type safety, so uses of it in application code should be carefully considered.

Requirements

Header: boost/asio/buffer.hpp

Convenience header: boost/asio.hpp

Provides support for implementing stackless coroutines.

class coroutine
Member Functions

Name

Description

coroutine

Constructs a coroutine in its initial state.

is_child

Returns true if the coroutine is the child of a fork.

is_complete

Returns true if the coroutine has reached its terminal state.

is_parent

Returns true if the coroutine is the parent of a fork.

The coroutine class may be used to implement stackless coroutines. The class itself is used to store the current state of the coroutine.

Coroutines are copy-constructible and assignable, and the space overhead is a single int. They can be used as a base class:

class session : coroutine
{
  ...
};

or as a data member:

class session
{
  ...
  coroutine coro_;
};

or even bound in as a function argument using lambdas or bind(). The important thing is that as the application maintains a copy of the object for as long as the coroutine must be kept alive.

Pseudo-keywords

A coroutine is used in conjunction with certain "pseudo-keywords", which are implemented as macros. These macros are defined by a header file:

#include <boost/asio/yield.hpp>

and may conversely be undefined as follows:

#include <boost/asio/unyield.hpp>

reenter

The reenter macro is used to define the body of a coroutine. It takes a single argument: a pointer or reference to a coroutine object. For example, if the base class is a coroutine object you may write:

reenter (this)
{
  ... coroutine body ...
}

and if a data member or other variable you can write:

reenter (coro_)
{
  ... coroutine body ...
}

When reenter is executed at runtime, control jumps to the location of the last yield or fork.

The coroutine body may also be a single statement, such as:

reenter (this) for (;;)
{
  ...
}

Limitation: The reenter macro is implemented using a switch. This means that you must take care when using local variables within the coroutine body. The local variable is not allowed in a position where reentering the coroutine could bypass the variable definition.

yield statement

This form of the yield keyword is often used with asynchronous operations:

yield socket_->async_read_some(buffer(*buffer_), *this);

This divides into four logical steps:

  • yield saves the current state of the coroutine.
  • The statement initiates the asynchronous operation.
  • The resume point is defined immediately following the statement.
  • Control is transferred to the end of the coroutine body.

When the asynchronous operation completes, the function object is invoked and reenter causes control to transfer to the resume point. It is important to remember to carry the coroutine state forward with the asynchronous operation. In the above snippet, the current class is a function object object with a coroutine object as base class or data member.

The statement may also be a compound statement, and this permits us to define local variables with limited scope:

yield
{
  mutable_buffers_1 b = buffer(*buffer_);
  socket_->async_read_some(b, *this);
}

yield return expression ;

This form of yield is often used in generators or coroutine-based parsers. For example, the function object:

struct interleave : coroutine
{
  istream& is1;
  istream& is2;
  char operator()(char c)
  {
    reenter (this) for (;;)
    {
      yield return is1.get();
      yield return is2.get();
    }
  }
};

defines a trivial coroutine that interleaves the characters from two input streams.

This type of yield divides into three logical steps:

  • yield saves the current state of the coroutine.
  • The resume point is defined immediately following the semicolon.
  • The value of the expression is returned from the function.

yield ;

This form of yield is equivalent to the following steps:

  • yield saves the current state of the coroutine.
  • The resume point is defined immediately following the semicolon.
  • Control is transferred to the end of the coroutine body.

This form might be applied when coroutines are used for cooperative threading and scheduling is explicitly managed. For example:

struct task : coroutine
{
  ...
  void operator()()
  {
    reenter (this)
    {
      while (... not finished ...)
      {
        ... do something ...
        yield;
        ... do some more ...
        yield;
      }
    }
  }
  ...
};
...
task t1, t2;
for (;;)
{
  t1();
  t2();
}

yield break ;

The final form of yield is used to explicitly terminate the coroutine. This form is comprised of two steps:

  • yield sets the coroutine state to indicate termination.
  • Control is transferred to the end of the coroutine body.

Once terminated, calls to is_complete() return true and the coroutine cannot be reentered.

Note that a coroutine may also be implicitly terminated if the coroutine body is exited without a yield, e.g. by return, throw or by running to the end of the body.

fork statement

The fork pseudo-keyword is used when "forking" a coroutine, i.e. splitting it into two (or more) copies. One use of fork is in a server, where a new coroutine is created to handle each client connection:

reenter (this)
{
  do
  {
    socket_.reset(new tcp::socket(io_service_));
    yield acceptor->async_accept(*socket_, *this);
    fork server(*this)();
  } while (is_parent());
  ... client-specific handling follows ...
}

The logical steps involved in a fork are:

  • fork saves the current state of the coroutine.
  • The statement creates a copy of the coroutine and either executes it immediately or schedules it for later execution.
  • The resume point is defined immediately following the semicolon.
  • For the "parent", control immediately continues from the next line.

The functions is_parent() and is_child() can be used to differentiate between parent and child. You would use these functions to alter subsequent control flow.

Note that fork doesn't do the actual forking by itself. It is the application's responsibility to create a clone of the coroutine and call it. The clone can be called immediately, as above, or scheduled for delayed execution using something like io_service::post().

Alternate macro names

If preferred, an application can use macro names that follow a more typical naming convention, rather than the pseudo-keywords. These are:

  • BOOST_ASIO_CORO_REENTER instead of reenter
  • BOOST_ASIO_CORO_YIELD instead of yield
  • BOOST_ASIO_CORO_FORK instead of fork
Requirements

Header: boost/asio/coroutine.hpp

Convenience header: boost/asio.hpp

Constructs a coroutine in its initial state.

coroutine();

Returns true if the coroutine is the child of a fork.

bool is_child() const;

Returns true if the coroutine has reached its terminal state.

bool is_complete() const;

Returns true if the coroutine is the parent of a fork.

bool is_parent() const;
datagram_socket_service::assign
datagram_socket_service::async_connect
datagram_socket_service::async_receive
datagram_socket_service::async_receive_from
datagram_socket_service::async_send
datagram_socket_service::async_send_to
datagram_socket_service::at_mark
datagram_socket_service::available
datagram_socket_service::bind
datagram_socket_service::cancel
datagram_socket_service::close
datagram_socket_service::connect
datagram_socket_service::construct
datagram_socket_service::converting_move_construct
datagram_socket_service::datagram_socket_service
datagram_socket_service::destroy
datagram_socket_service::endpoint_type
datagram_socket_service::get_io_service
datagram_socket_service::get_option
datagram_socket_service::id
datagram_socket_service::implementation_type
datagram_socket_service::io_control
datagram_socket_service::is_open
datagram_socket_service::local_endpoint
datagram_socket_service::move_assign
datagram_socket_service::move_construct
datagram_socket_service::native
datagram_socket_service::native_handle
datagram_socket_service::native_handle_type
datagram_socket_service::native_non_blocking
datagram_socket_service::native_type
datagram_socket_service::non_blocking
datagram_socket_service::open
datagram_socket_service::protocol_type
datagram_socket_service::receive
datagram_socket_service::receive_from
datagram_socket_service::remote_endpoint
datagram_socket_service::send
datagram_socket_service::send_to
datagram_socket_service::set_option
datagram_socket_service::shutdown

Default service implementation for a datagram socket.

template<
    typename Protocol>
class datagram_socket_service :
  public io_service::service
Types

Name

Description

endpoint_type

The endpoint type.

implementation_type

The type of a datagram socket.

native_handle_type

The native socket type.

native_type

(Deprecated: Use native_handle_type.) The native socket type.

protocol_type

The protocol type.

Member Functions

Name

Description

assign

Assign an existing native socket to a datagram socket.

async_connect

Start an asynchronous connect.

async_receive

Start an asynchronous receive.

async_receive_from

Start an asynchronous receive that will get the endpoint of the sender.

async_send

Start an asynchronous send.

async_send_to

Start an asynchronous send.

at_mark

Determine whether the socket is at the out-of-band data mark.

available

Determine the number of bytes available for reading.

bind

cancel

Cancel all asynchronous operations associated with the socket.

close

Close a datagram socket implementation.

connect

Connect the datagram socket to the specified endpoint.

construct

Construct a new datagram socket implementation.

converting_move_construct

Move-construct a new datagram socket implementation from another protocol type.

datagram_socket_service

Construct a new datagram socket service for the specified io_service.

destroy

Destroy a datagram socket implementation.

get_io_service

Get the io_service object that owns the service.

get_option

Get a socket option.

io_control

Perform an IO control command on the socket.

is_open

Determine whether the socket is open.

local_endpoint

Get the local endpoint.

move_assign

Move-assign from another datagram socket implementation.

move_construct

Move-construct a new datagram socket implementation.

native

(Deprecated: Use native_handle().) Get the native socket implementation.

native_handle

Get the native socket implementation.

native_non_blocking

Gets the non-blocking mode of the native socket implementation.

Sets the non-blocking mode of the native socket implementation.

non_blocking

Gets the non-blocking mode of the socket.

Sets the non-blocking mode of the socket.

open

receive

Receive some data from the peer.

receive_from

Receive a datagram with the endpoint of the sender.

remote_endpoint

Get the remote endpoint.

send

Send the given data to the peer.

send_to

Send a datagram to the specified endpoint.

set_option

Set a socket option.

shutdown

Disable sends or receives on the socket.

Data Members

Name

Description

id

The unique service identifier.

Requirements

Header: boost/asio/datagram_socket_service.hpp

Convenience header: boost/asio.hpp

Assign an existing native socket to a datagram socket.

boost::system::error_code assign(
    implementation_type & impl,
    const protocol_type & protocol,
    const native_handle_type & native_socket,
    boost::system::error_code & ec);

Start an asynchronous connect.

template<
    typename ConnectHandler>
void-or-deduced async_connect(
    implementation_type & impl,
    const endpoint_type & peer_endpoint,
    ConnectHandler handler);

Start an asynchronous receive.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_receive(
    implementation_type & impl,
    const MutableBufferSequence & buffers,
    socket_base::message_flags flags,
    ReadHandler handler);

Start an asynchronous receive that will get the endpoint of the sender.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_receive_from(
    implementation_type & impl,
    const MutableBufferSequence & buffers,
    endpoint_type & sender_endpoint,
    socket_base::message_flags flags,
    ReadHandler handler);

Start an asynchronous send.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_send(
    implementation_type & impl,
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags,
    WriteHandler handler);

Start an asynchronous send.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_send_to(
    implementation_type & impl,
    const ConstBufferSequence & buffers,
    const endpoint_type & destination,
    socket_base::message_flags flags,
    WriteHandler handler);

Determine whether the socket is at the out-of-band data mark.

bool at_mark(
    const implementation_type & impl,
    boost::system::error_code & ec) const;

Determine the number of bytes available for reading.

std::size_t available(
    const implementation_type & impl,
    boost::system::error_code & ec) const;

boost::system::error_code bind(
    implementation_type & impl,
    const endpoint_type & endpoint,
    boost::system::error_code & ec);

Cancel all asynchronous operations associated with the socket.

boost::system::error_code cancel(
    implementation_type & impl,
    boost::system::error_code & ec);

Close a datagram socket implementation.

boost::system::error_code close(
    implementation_type & impl,
    boost::system::error_code & ec);

Connect the datagram socket to the specified endpoint.

boost::system::error_code connect(
    implementation_type & impl,
    const endpoint_type & peer_endpoint,
    boost::system::error_code & ec);

Construct a new datagram socket implementation.

void construct(
    implementation_type & impl);

Move-construct a new datagram socket implementation from another protocol type.

template<
    typename Protocol1>
void converting_move_construct(
    implementation_type & impl,
    typename datagram_socket_service< Protocol1 >::implementation_type & other_impl,
    typename enable_if< is_convertible< Protocol1, Protocol >::value >::type *  = 0);

Construct a new datagram socket service for the specified io_service.

datagram_socket_service(
    boost::asio::io_service & io_service);

Destroy a datagram socket implementation.

void destroy(
    implementation_type & impl);

The endpoint type.

typedef Protocol::endpoint endpoint_type;
Requirements

Header: boost/asio/datagram_socket_service.hpp

Convenience header: boost/asio.hpp

Inherited from io_service.

Get the io_service object that owns the service.

boost::asio::io_service & get_io_service();

Get a socket option.

template<
    typename GettableSocketOption>
boost::system::error_code get_option(
    const implementation_type & impl,
    GettableSocketOption & option,
    boost::system::error_code & ec) const;

The unique service identifier.

static boost::asio::io_service::id id;

The type of a datagram socket.

typedef implementation_defined implementation_type;
Requirements

Header: boost/asio/datagram_socket_service.hpp

Convenience header: boost/asio.hpp

Perform an IO control command on the socket.

template<
    typename IoControlCommand>
boost::system::error_code io_control(
    implementation_type & impl,
    IoControlCommand & command,
    boost::system::error_code & ec);

Determine whether the socket is open.

bool is_open(
    const implementation_type & impl) const;

Get the local endpoint.

endpoint_type local_endpoint(
    const implementation_type & impl,
    boost::system::error_code & ec) const;

Move-assign from another datagram socket implementation.

void move_assign(
    implementation_type & impl,
    datagram_socket_service & other_service,
    implementation_type & other_impl);

Move-construct a new datagram socket implementation.

void move_construct(
    implementation_type & impl,
    implementation_type & other_impl);

(Deprecated: Use native_handle().) Get the native socket implementation.

native_type native(
    implementation_type & impl);

Get the native socket implementation.

native_handle_type native_handle(
    implementation_type & impl);

The native socket type.

typedef implementation_defined native_handle_type;
Requirements

Header: boost/asio/datagram_socket_service.hpp

Convenience header: boost/asio.hpp

Gets the non-blocking mode of the native socket implementation.

bool native_non_blocking(
    const implementation_type & impl) const;
  » more...

Sets the non-blocking mode of the native socket implementation.

boost::system::error_code native_non_blocking(
    implementation_type & impl,
    bool mode,
    boost::system::error_code & ec);
  » more...

Gets the non-blocking mode of the native socket implementation.

bool native_non_blocking(
    const implementation_type & impl) const;

Sets the non-blocking mode of the native socket implementation.

boost::system::error_code native_non_blocking(
    implementation_type & impl,
    bool mode,
    boost::system::error_code & ec);

(Deprecated: Use native_handle_type.) The native socket type.

typedef implementation_defined native_type;
Requirements

Header: boost/asio/datagram_socket_service.hpp

Convenience header: boost/asio.hpp

Gets the non-blocking mode of the socket.

bool non_blocking(
    const implementation_type & impl) const;
  » more...

Sets the non-blocking mode of the socket.

boost::system::error_code non_blocking(
    implementation_type & impl,
    bool mode,
    boost::system::error_code & ec);
  » more...

Gets the non-blocking mode of the socket.

bool non_blocking(
    const implementation_type & impl) const;

Sets the non-blocking mode of the socket.

boost::system::error_code non_blocking(
    implementation_type & impl,
    bool mode,
    boost::system::error_code & ec);

boost::system::error_code open(
    implementation_type & impl,
    const protocol_type & protocol,
    boost::system::error_code & ec);

The protocol type.

typedef Protocol protocol_type;
Requirements

Header: boost/asio/datagram_socket_service.hpp

Convenience header: boost/asio.hpp

Receive some data from the peer.

template<
    typename MutableBufferSequence>
std::size_t receive(
    implementation_type & impl,
    const MutableBufferSequence & buffers,
    socket_base::message_flags flags,
    boost::system::error_code & ec);

Receive a datagram with the endpoint of the sender.

template<
    typename MutableBufferSequence>
std::size_t receive_from(
    implementation_type & impl,
    const MutableBufferSequence & buffers,
    endpoint_type & sender_endpoint,
    socket_base::message_flags flags,
    boost::system::error_code & ec);

Get the remote endpoint.

endpoint_type remote_endpoint(
    const implementation_type & impl,
    boost::system::error_code & ec) const;

Send the given data to the peer.

template<
    typename ConstBufferSequence>
std::size_t send(
    implementation_type & impl,
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags,
    boost::system::error_code & ec);

Send a datagram to the specified endpoint.

template<
    typename ConstBufferSequence>
std::size_t send_to(
    implementation_type & impl,
    const ConstBufferSequence & buffers,
    const endpoint_type & destination,
    socket_base::message_flags flags,
    boost::system::error_code & ec);

Set a socket option.

template<
    typename SettableSocketOption>
boost::system::error_code set_option(
    implementation_type & impl,
    const SettableSocketOption & option,
    boost::system::error_code & ec);

Disable sends or receives on the socket.

boost::system::error_code shutdown(
    implementation_type & impl,
    socket_base::shutdown_type what,
    boost::system::error_code & ec);

Typedef for the typical usage of timer. Uses a UTC clock.

typedef basic_deadline_timer< boost::posix_time::ptime > deadline_timer;
Types

Name

Description

duration_type

The duration type.

implementation_type

The underlying implementation type of I/O object.

service_type

The type of the service that will be used to provide I/O operations.

time_type

The time type.

traits_type

The time traits type.

Member Functions

Name

Description

async_wait

Start an asynchronous wait on the timer.

basic_deadline_timer

Constructor.

Constructor to set a particular expiry time as an absolute time.

Constructor to set a particular expiry time relative to now.

cancel

Cancel any asynchronous operations that are waiting on the timer.

cancel_one

Cancels one asynchronous operation that is waiting on the timer.

expires_at

Get the timer's expiry time as an absolute time.

Set the timer's expiry time as an absolute time.

expires_from_now

Get the timer's expiry time relative to now.

Set the timer's expiry time relative to now.

get_io_service

Get the io_service associated with the object.

wait

Perform a blocking wait on the timer.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_deadline_timer class template provides the ability to perform a blocking or asynchronous wait for a timer to expire.

A deadline timer is always in one of two states: "expired" or "not expired". If the wait() or async_wait() function is called on an expired timer, the wait operation will complete immediately.

Most applications will use the deadline_timer typedef.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Examples

Performing a blocking wait:

// Construct a timer without setting an expiry time.
boost::asio::deadline_timer timer(io_service);

// Set an expiry time relative to now.
timer.expires_from_now(boost::posix_time::seconds(5));

// Wait for the timer to expire.
timer.wait();

Performing an asynchronous wait:

void handler(const boost::system::error_code& error)
{
  if (!error)
  {
    // Timer expired.
  }
}

...

// Construct a timer with an absolute expiry time.
boost::asio::deadline_timer timer(io_service,
    boost::posix_time::time_from_string("2005-12-07 23:59:59.000"));

// Start an asynchronous wait.
timer.async_wait(handler);
Changing an active deadline_timer's expiry time

Changing the expiry time of a timer while there are pending asynchronous waits causes those wait operations to be cancelled. To ensure that the action associated with the timer is performed only once, use something like this: used:

void on_some_event()
{
  if (my_timer.expires_from_now(seconds(5)) > 0)
  {
    // We managed to cancel the timer. Start new asynchronous wait.
    my_timer.async_wait(on_timeout);
  }
  else
  {
    // Too late, timer has already expired!
  }
}

void on_timeout(const boost::system::error_code& e)
{
  if (e != boost::asio::error::operation_aborted)
  {
    // Timer was not cancelled, take necessary action.
  }
}
  • The boost::asio::basic_deadline_timer::expires_from_now() function cancels any pending asynchronous waits, and returns the number of asynchronous waits that were cancelled. If it returns 0 then you were too late and the wait handler has already been executed, or will soon be executed. If it returns 1 then the wait handler was successfully cancelled.
  • If a wait handler is cancelled, the boost::system::error_code passed to it contains the value boost::asio::error::operation_aborted.
Requirements

Header: boost/asio/deadline_timer.hpp

Convenience header: boost/asio.hpp

Default service implementation for a timer.

template<
    typename TimeType,
    typename TimeTraits = boost::asio::time_traits<TimeType>>
class deadline_timer_service :
  public io_service::service
Types

Name

Description

duration_type

The duration type.

implementation_type

The implementation type of the deadline timer.

time_type

The time type.

traits_type

The time traits type.

Member Functions

Name

Description

async_wait

cancel

Cancel any asynchronous wait operations associated with the timer.

cancel_one

Cancels one asynchronous wait operation associated with the timer.

construct

Construct a new timer implementation.

deadline_timer_service

Construct a new timer service for the specified io_service.

destroy

Destroy a timer implementation.

expires_at

Get the expiry time for the timer as an absolute time.

Set the expiry time for the timer as an absolute time.

expires_from_now

Get the expiry time for the timer relative to now.

Set the expiry time for the timer relative to now.

get_io_service

Get the io_service object that owns the service.

wait

Data Members

Name

Description

id

The unique service identifier.

Requirements

Header: boost/asio/deadline_timer_service.hpp

Convenience header: boost/asio.hpp

template<
    typename WaitHandler>
void-or-deduced async_wait(
    implementation_type & impl,
    WaitHandler handler);

Cancel any asynchronous wait operations associated with the timer.

std::size_t cancel(
    implementation_type & impl,
    boost::system::error_code & ec);

Cancels one asynchronous wait operation associated with the timer.

std::size_t cancel_one(
    implementation_type & impl,
    boost::system::error_code & ec);

Construct a new timer implementation.

void construct(
    implementation_type & impl);

Construct a new timer service for the specified io_service.

deadline_timer_service(
    boost::asio::io_service & io_service);

Destroy a timer implementation.

void destroy(
    implementation_type & impl);

The duration type.

typedef traits_type::duration_type duration_type;
Requirements

Header: boost/asio/deadline_timer_service.hpp

Convenience header: boost/asio.hpp

Get the expiry time for the timer as an absolute time.

time_type expires_at(
    const implementation_type & impl) const;
  » more...

Set the expiry time for the timer as an absolute time.

std::size_t expires_at(
    implementation_type & impl,
    const time_type & expiry_time,
    boost::system::error_code & ec);
  » more...

Get the expiry time for the timer as an absolute time.

time_type expires_at(
    const implementation_type & impl) const;

Set the expiry time for the timer as an absolute time.

std::size_t expires_at(
    implementation_type & impl,
    const time_type & expiry_time,
    boost::system::error_code & ec);

Get the expiry time for the timer relative to now.

duration_type expires_from_now(
    const implementation_type & impl) const;
  » more...

Set the expiry time for the timer relative to now.

std::size_t expires_from_now(
    implementation_type & impl,
    const duration_type & expiry_time,
    boost::system::error_code & ec);
  » more...

Get the expiry time for the timer relative to now.

duration_type expires_from_now(
    const implementation_type & impl) const;

Set the expiry time for the timer relative to now.

std::size_t expires_from_now(
    implementation_type & impl,
    const duration_type & expiry_time,
    boost::system::error_code & ec);

Inherited from io_service.

Get the io_service object that owns the service.

boost::asio::io_service & get_io_service();

The unique service identifier.

static boost::asio::io_service::id id;

The implementation type of the deadline timer.

typedef implementation_defined implementation_type;
Requirements

Header: boost/asio/deadline_timer_service.hpp

Convenience header: boost/asio.hpp

The time type.

typedef traits_type::time_type time_type;
Requirements

Header: boost/asio/deadline_timer_service.hpp

Convenience header: boost/asio.hpp

The time traits type.

typedef TimeTraits traits_type;
Requirements

Header: boost/asio/deadline_timer_service.hpp

Convenience header: boost/asio.hpp

void wait(
    implementation_type & impl,
    boost::system::error_code & ec);

static const boost::system::error_category & addrinfo_category = boost::asio::error::get_addrinfo_category();
Requirements

Header: boost/asio/error.hpp

Convenience header: boost/asio.hpp

enum addrinfo_errors

Values

service_not_found

The service is not supported for the given socket type.

socket_type_not_supported

The socket type is not supported.

Requirements

Header: boost/asio/error.hpp

Convenience header: boost/asio.hpp

enum basic_errors

Values

access_denied

Permission denied.

address_family_not_supported

Address family not supported by protocol.

address_in_use

Address already in use.

already_connected

Transport endpoint is already connected.

already_started

Operation already in progress.

broken_pipe

Broken pipe.

connection_aborted

A connection has been aborted.

connection_refused

Connection refused.

connection_reset

Connection reset by peer.

bad_descriptor

Bad file descriptor.

fault

Bad address.

host_unreachable

No route to host.

in_progress

Operation now in progress.

interrupted

Interrupted system call.

invalid_argument

Invalid argument.

message_size

Message too long.

name_too_long

The name was too long.

network_down

Network is down.

network_reset

Network dropped connection on reset.

network_unreachable

Network is unreachable.

no_descriptors

Too many open files.

no_buffer_space

No buffer space available.

no_memory

Cannot allocate memory.

no_permission

Operation not permitted.

no_protocol_option

Protocol not available.

no_such_device

No such device.

not_connected

Transport endpoint is not connected.

not_socket

Socket operation on non-socket.

operation_aborted

Operation cancelled.

operation_not_supported

Operation not supported.

shut_down

Cannot send after transport endpoint shutdown.

timed_out

Connection timed out.

try_again

Resource temporarily unavailable.

would_block

The socket is marked non-blocking and the requested operation would block.

Requirements

Header: boost/asio/error.hpp

Convenience header: boost/asio.hpp

const boost::system::error_category & get_addrinfo_category();
Requirements

Header: boost/asio/error.hpp

Convenience header: boost/asio.hpp

const boost::system::error_category & get_misc_category();
Requirements

Header: boost/asio/error.hpp

Convenience header: boost/asio.hpp

const boost::system::error_category & get_netdb_category();
Requirements

Header: boost/asio/error.hpp

Convenience header: boost/asio.hpp

const boost::system::error_category & get_ssl_category();
Requirements

Header: boost/asio/ssl/error.hpp

Convenience header: boost/asio/ssl.hpp

const boost::system::error_category & get_system_category();
Requirements

Header: boost/asio/error.hpp

Convenience header: boost/asio.hpp

boost::system::error_code make_error_code(
    basic_errors e);
  » more...

boost::system::error_code make_error_code(
    netdb_errors e);
  » more...

boost::system::error_code make_error_code(
    addrinfo_errors e);
  » more...

boost::system::error_code make_error_code(
    misc_errors e);
  » more...

boost::system::error_code make_error_code(
    ssl_errors e);
  » more...
Requirements

Header: boost/asio/error.hpp

Convenience header: boost/asio.hpp

boost::system::error_code make_error_code(
    basic_errors e);
boost::system::error_code make_error_code(
    netdb_errors e);
boost::system::error_code make_error_code(
    addrinfo_errors e);
boost::system::error_code make_error_code(
    misc_errors e);
boost::system::error_code make_error_code(
    ssl_errors e);

static const boost::system::error_category & misc_category = boost::asio::error::get_misc_category();
Requirements

Header: boost/asio/error.hpp

Convenience header: boost/asio.hpp

enum misc_errors

Values

already_open

Already open.

eof

End of file or stream.

not_found

Element not found.

fd_set_failure

The descriptor cannot fit into the select system call's fd_set.

Requirements

Header: boost/asio/error.hpp

Convenience header: boost/asio.hpp

static const boost::system::error_category & netdb_category = boost::asio::error::get_netdb_category();
Requirements

Header: boost/asio/error.hpp

Convenience header: boost/asio.hpp

enum netdb_errors

Values

host_not_found

Host not found (authoritative).

host_not_found_try_again

Host not found (non-authoritative).

no_data

The query is valid but does not have associated address data.

no_recovery

A non-recoverable error occurred.

Requirements

Header: boost/asio/error.hpp

Convenience header: boost/asio.hpp

static const boost::system::error_category & ssl_category = boost::asio::error::get_ssl_category();
Requirements

Header: boost/asio/ssl/error.hpp

Convenience header: boost/asio/ssl.hpp

enum ssl_errors
Requirements

Header: boost/asio/ssl/error.hpp

Convenience header: boost/asio/ssl.hpp

static const boost::system::error_category & system_category = boost::asio::error::get_system_category();
Requirements

Header: boost/asio/error.hpp

Convenience header: boost/asio.hpp

Describes an endpoint for any socket type.

template<
    typename Protocol>
class basic_endpoint
Types

Name

Description

data_type

The type of the endpoint structure. This type is dependent on the underlying implementation of the socket layer.

protocol_type

The protocol type associated with the endpoint.

Member Functions

Name

Description

basic_endpoint

Default constructor.

Construct an endpoint from the specified socket address.

Construct an endpoint from the specific endpoint type.

Copy constructor.

capacity

Get the capacity of the endpoint in the native type.

data

Get the underlying endpoint in the native type.

operator=

Assign from another endpoint.

protocol

The protocol associated with the endpoint.

resize

Set the underlying size of the endpoint in the native type.

size

Get the underlying size of the endpoint in the native type.

Friends

Name

Description

operator!=

Compare two endpoints for inequality.

operator<

Compare endpoints for ordering.

operator<=

Compare endpoints for ordering.

operator==

Compare two endpoints for equality.

operator>

Compare endpoints for ordering.

operator>=

Compare endpoints for ordering.

The generic::basic_endpoint class template describes an endpoint that may be associated with any socket type.

Remarks

The socket types sockaddr type must be able to fit into a sockaddr_storage structure.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/generic/basic_endpoint.hpp

Convenience header: boost/asio.hpp

Default constructor.

basic_endpoint();
  » more...

Construct an endpoint from the specified socket address.

basic_endpoint(
    const void * socket_address,
    std::size_t socket_address_size,
    int socket_protocol = 0);
  » more...

Construct an endpoint from the specific endpoint type.

template<
    typename Endpoint>
basic_endpoint(
    const Endpoint & endpoint);
  » more...

Copy constructor.

basic_endpoint(
    const basic_endpoint & other);
  » more...

Default constructor.

basic_endpoint();

Construct an endpoint from the specified socket address.

basic_endpoint(
    const void * socket_address,
    std::size_t socket_address_size,
    int socket_protocol = 0);

Construct an endpoint from the specific endpoint type.

template<
    typename Endpoint>
basic_endpoint(
    const Endpoint & endpoint);

Copy constructor.

basic_endpoint(
    const basic_endpoint & other);

Get the capacity of the endpoint in the native type.

std::size_t capacity() const;

Get the underlying endpoint in the native type.

data_type * data();
  » more...

const data_type * data() const;
  » more...

Get the underlying endpoint in the native type.

data_type * data();

Get the underlying endpoint in the native type.

const data_type * data() const;

The type of the endpoint structure. This type is dependent on the underlying implementation of the socket layer.

typedef implementation_defined data_type;
Requirements

Header: boost/asio/generic/basic_endpoint.hpp

Convenience header: boost/asio.hpp

Compare two endpoints for inequality.

friend bool operator!=(
    const basic_endpoint< Protocol > & e1,
    const basic_endpoint< Protocol > & e2);
Requirements

Header: boost/asio/generic/basic_endpoint.hpp

Convenience header: boost/asio.hpp

Compare endpoints for ordering.

friend bool operator<(
    const basic_endpoint< Protocol > & e1,
    const basic_endpoint< Protocol > & e2);
Requirements

Header: boost/asio/generic/basic_endpoint.hpp

Convenience header: boost/asio.hpp

Compare endpoints for ordering.

friend bool operator<=(
    const basic_endpoint< Protocol > & e1,
    const basic_endpoint< Protocol > & e2);
Requirements

Header: boost/asio/generic/basic_endpoint.hpp

Convenience header: boost/asio.hpp

Assign from another endpoint.

basic_endpoint & operator=(
    const basic_endpoint & other);

Compare two endpoints for equality.

friend bool operator==(
    const basic_endpoint< Protocol > & e1,
    const basic_endpoint< Protocol > & e2);
Requirements

Header: boost/asio/generic/basic_endpoint.hpp

Convenience header: boost/asio.hpp

Compare endpoints for ordering.

friend bool operator>(
    const basic_endpoint< Protocol > & e1,
    const basic_endpoint< Protocol > & e2);
Requirements

Header: boost/asio/generic/basic_endpoint.hpp

Convenience header: boost/asio.hpp

Compare endpoints for ordering.

friend bool operator>=(
    const basic_endpoint< Protocol > & e1,
    const basic_endpoint< Protocol > & e2);
Requirements

Header: boost/asio/generic/basic_endpoint.hpp

Convenience header: boost/asio.hpp

The protocol associated with the endpoint.

protocol_type protocol() const;

The protocol type associated with the endpoint.

typedef Protocol protocol_type;
Requirements

Header: boost/asio/generic/basic_endpoint.hpp

Convenience header: boost/asio.hpp

Set the underlying size of the endpoint in the native type.

void resize(
    std::size_t new_size);

Get the underlying size of the endpoint in the native type.

std::size_t size() const;

Encapsulates the flags needed for a generic datagram-oriented socket.

class datagram_protocol
Types

Name

Description

endpoint

The type of an endpoint.

socket

The generic socket type.

Member Functions

Name

Description

datagram_protocol

Construct a protocol object for a specific address family and protocol.

Construct a generic protocol object from a specific protocol.

family

Obtain an identifier for the protocol family.

protocol

Obtain an identifier for the protocol.

type

Obtain an identifier for the type of the protocol.

Friends

Name

Description

operator!=

Compare two protocols for inequality.

operator==

Compare two protocols for equality.

The generic::datagram_protocol class contains flags necessary for datagram-oriented sockets of any address family and protocol.

Examples

Constructing using a native address family and socket protocol:

datagram_protocol p(AF_INET, IPPROTO_UDP);

Constructing from a specific protocol type:

datagram_protocol p(boost::asio::ip::udp::v4());
Thread Safety

Distinct objects: Safe.

Shared objects: Safe.

Requirements

Header: boost/asio/generic/datagram_protocol.hpp

Convenience header: boost/asio.hpp

Construct a protocol object for a specific address family and protocol.

datagram_protocol(
    int address_family,
    int socket_protocol);
  » more...

Construct a generic protocol object from a specific protocol.

template<
    typename Protocol>
datagram_protocol(
    const Protocol & source_protocol);
  » more...

Construct a protocol object for a specific address family and protocol.

datagram_protocol(
    int address_family,
    int socket_protocol);

Construct a generic protocol object from a specific protocol.

template<
    typename Protocol>
datagram_protocol(
    const Protocol & source_protocol);
Exceptions

@c

bad_cast Thrown if the source protocol is not datagram-oriented.

The type of an endpoint.

typedef basic_endpoint< datagram_protocol > endpoint;
Types

Name

Description

data_type

The type of the endpoint structure. This type is dependent on the underlying implementation of the socket layer.

protocol_type

The protocol type associated with the endpoint.

Member Functions

Name

Description

basic_endpoint

Default constructor.

Construct an endpoint from the specified socket address.

Construct an endpoint from the specific endpoint type.

Copy constructor.

capacity

Get the capacity of the endpoint in the native type.

data

Get the underlying endpoint in the native type.

operator=

Assign from another endpoint.

protocol

The protocol associated with the endpoint.

resize

Set the underlying size of the endpoint in the native type.

size

Get the underlying size of the endpoint in the native type.

Friends

Name

Description

operator!=

Compare two endpoints for inequality.

operator<

Compare endpoints for ordering.

operator<=

Compare endpoints for ordering.

operator==

Compare two endpoints for equality.

operator>

Compare endpoints for ordering.

operator>=

Compare endpoints for ordering.

The generic::basic_endpoint class template describes an endpoint that may be associated with any socket type.

Remarks

The socket types sockaddr type must be able to fit into a sockaddr_storage structure.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/generic/datagram_protocol.hpp

Convenience header: boost/asio.hpp

Obtain an identifier for the protocol family.

int family() const;

Compare two protocols for inequality.

friend bool operator!=(
    const datagram_protocol & p1,
    const datagram_protocol & p2);
Requirements

Header: boost/asio/generic/datagram_protocol.hpp

Convenience header: boost/asio.hpp

Compare two protocols for equality.

friend bool operator==(
    const datagram_protocol & p1,
    const datagram_protocol & p2);
Requirements

Header: boost/asio/generic/datagram_protocol.hpp

Convenience header: boost/asio.hpp

Obtain an identifier for the protocol.

int protocol() const;

The generic socket type.

typedef basic_datagram_socket< datagram_protocol > socket;
Types

Name

Description

broadcast

Socket option to permit sending of broadcast messages.

bytes_readable

IO control command to get the amount of data that can be read without blocking.

debug

Socket option to enable socket-level debugging.

do_not_route

Socket option to prevent routing, use local interfaces only.

enable_connection_aborted

Socket option to report aborted connections on accept.

endpoint_type

The endpoint type.

implementation_type

The underlying implementation type of I/O object.

keep_alive

Socket option to send keep-alives.

linger

Socket option to specify whether the socket lingers on close if unsent data is present.

lowest_layer_type

A basic_socket is always the lowest layer.

message_flags

Bitmask type for flags that can be passed to send and receive operations.

native_handle_type

The native representation of a socket.

native_type

(Deprecated: Use native_handle_type.) The native representation of a socket.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

protocol_type

The protocol type.

receive_buffer_size

Socket option for the receive buffer size of a socket.

receive_low_watermark

Socket option for the receive low watermark.

reuse_address

Socket option to allow the socket to be bound to an address that is already in use.

send_buffer_size

Socket option for the send buffer size of a socket.

send_low_watermark

Socket option for the send low watermark.

service_type

The type of the service that will be used to provide I/O operations.

shutdown_type

Different ways a socket may be shutdown.

Member Functions

Name

Description

assign

Assign an existing native socket to the socket.

async_connect

Start an asynchronous connect.

async_receive

Start an asynchronous receive on a connected socket.

async_receive_from

Start an asynchronous receive.

async_send

Start an asynchronous send on a connected socket.

async_send_to

Start an asynchronous send.

at_mark

Determine whether the socket is at the out-of-band data mark.

available

Determine the number of bytes available for reading.

basic_datagram_socket

Construct a basic_datagram_socket without opening it.

Construct and open a basic_datagram_socket.

Construct a basic_datagram_socket, opening it and binding it to the given local endpoint.

Construct a basic_datagram_socket on an existing native socket.

Move-construct a basic_datagram_socket from another.

Move-construct a basic_datagram_socket from a socket of another protocol type.

bind

Bind the socket to the given local endpoint.

cancel

Cancel all asynchronous operations associated with the socket.

close

Close the socket.

connect

Connect the socket to the specified endpoint.

get_io_service

Get the io_service associated with the object.

get_option

Get an option from the socket.

io_control

Perform an IO control command on the socket.

is_open

Determine whether the socket is open.

local_endpoint

Get the local endpoint of the socket.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native socket representation.

native_handle

Get the native socket representation.

native_non_blocking

Gets the non-blocking mode of the native socket implementation.

Sets the non-blocking mode of the native socket implementation.

non_blocking

Gets the non-blocking mode of the socket.

Sets the non-blocking mode of the socket.

open

Open the socket using the specified protocol.

operator=

Move-assign a basic_datagram_socket from another.

Move-assign a basic_datagram_socket from a socket of another protocol type.

receive

Receive some data on a connected socket.

receive_from

Receive a datagram with the endpoint of the sender.

remote_endpoint

Get the remote endpoint of the socket.

send

Send some data on a connected socket.

send_to

Send a datagram to the specified endpoint.

set_option

Set an option on the socket.

shutdown

Disable sends or receives on the socket.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Data Members

Name

Description

max_connections

The maximum length of the queue of pending incoming connections.

message_do_not_route

Specify that the data should not be subject to routing.

message_end_of_record

Specifies that the data marks the end of a record.

message_out_of_band

Process out-of-band data.

message_peek

Peek at incoming data without removing it from the input queue.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_datagram_socket class template provides asynchronous and blocking datagram-oriented socket functionality.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/generic/datagram_protocol.hpp

Convenience header: boost/asio.hpp

Obtain an identifier for the type of the protocol.

int type() const;

Encapsulates the flags needed for a generic raw socket.

class raw_protocol
Types

Name

Description

endpoint

The type of an endpoint.

socket

The generic socket type.

Member Functions

Name

Description

family

Obtain an identifier for the protocol family.

protocol

Obtain an identifier for the protocol.

raw_protocol

Construct a protocol object for a specific address family and protocol.

Construct a generic protocol object from a specific protocol.

type

Obtain an identifier for the type of the protocol.

Friends

Name

Description

operator!=

Compare two protocols for inequality.

operator==

Compare two protocols for equality.

The generic::raw_protocol class contains flags necessary for raw sockets of any address family and protocol.

Examples

Constructing using a native address family and socket protocol:

raw_protocol p(AF_INET, IPPROTO_ICMP);

Constructing from a specific protocol type:

raw_protocol p(boost::asio::ip::icmp::v4());
Thread Safety

Distinct objects: Safe.

Shared objects: Safe.

Requirements

Header: boost/asio/generic/raw_protocol.hpp

Convenience header: boost/asio.hpp

The type of an endpoint.

typedef basic_endpoint< raw_protocol > endpoint;
Types

Name

Description

data_type

The type of the endpoint structure. This type is dependent on the underlying implementation of the socket layer.

protocol_type

The protocol type associated with the endpoint.

Member Functions

Name

Description

basic_endpoint

Default constructor.

Construct an endpoint from the specified socket address.

Construct an endpoint from the specific endpoint type.

Copy constructor.

capacity

Get the capacity of the endpoint in the native type.

data

Get the underlying endpoint in the native type.

operator=

Assign from another endpoint.

protocol

The protocol associated with the endpoint.

resize

Set the underlying size of the endpoint in the native type.

size

Get the underlying size of the endpoint in the native type.

Friends

Name

Description

operator!=

Compare two endpoints for inequality.

operator<

Compare endpoints for ordering.

operator<=

Compare endpoints for ordering.

operator==

Compare two endpoints for equality.

operator>

Compare endpoints for ordering.

operator>=

Compare endpoints for ordering.

The generic::basic_endpoint class template describes an endpoint that may be associated with any socket type.

Remarks

The socket types sockaddr type must be able to fit into a sockaddr_storage structure.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/generic/raw_protocol.hpp

Convenience header: boost/asio.hpp

Obtain an identifier for the protocol family.

int family() const;

Compare two protocols for inequality.

friend bool operator!=(
    const raw_protocol & p1,
    const raw_protocol & p2);
Requirements

Header: boost/asio/generic/raw_protocol.hpp

Convenience header: boost/asio.hpp

Compare two protocols for equality.

friend bool operator==(
    const raw_protocol & p1,
    const raw_protocol & p2);
Requirements

Header: boost/asio/generic/raw_protocol.hpp

Convenience header: boost/asio.hpp

Obtain an identifier for the protocol.

int protocol() const;

Construct a protocol object for a specific address family and protocol.

raw_protocol(
    int address_family,
    int socket_protocol);
  » more...

Construct a generic protocol object from a specific protocol.

template<
    typename Protocol>
raw_protocol(
    const Protocol & source_protocol);
  » more...

Construct a protocol object for a specific address family and protocol.

raw_protocol(
    int address_family,
    int socket_protocol);

Construct a generic protocol object from a specific protocol.

template<
    typename Protocol>
raw_protocol(
    const Protocol & source_protocol);
Exceptions

@c

bad_cast Thrown if the source protocol is not raw-oriented.

The generic socket type.

typedef basic_raw_socket< raw_protocol > socket;
Types

Name

Description

broadcast

Socket option to permit sending of broadcast messages.

bytes_readable

IO control command to get the amount of data that can be read without blocking.

debug

Socket option to enable socket-level debugging.

do_not_route

Socket option to prevent routing, use local interfaces only.

enable_connection_aborted

Socket option to report aborted connections on accept.

endpoint_type

The endpoint type.

implementation_type

The underlying implementation type of I/O object.

keep_alive

Socket option to send keep-alives.

linger

Socket option to specify whether the socket lingers on close if unsent data is present.

lowest_layer_type

A basic_socket is always the lowest layer.

message_flags

Bitmask type for flags that can be passed to send and receive operations.

native_handle_type

The native representation of a socket.

native_type

(Deprecated: Use native_handle_type.) The native representation of a socket.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

protocol_type

The protocol type.

receive_buffer_size

Socket option for the receive buffer size of a socket.

receive_low_watermark

Socket option for the receive low watermark.

reuse_address

Socket option to allow the socket to be bound to an address that is already in use.

send_buffer_size

Socket option for the send buffer size of a socket.

send_low_watermark

Socket option for the send low watermark.

service_type

The type of the service that will be used to provide I/O operations.

shutdown_type

Different ways a socket may be shutdown.

Member Functions

Name

Description

assign

Assign an existing native socket to the socket.

async_connect

Start an asynchronous connect.

async_receive

Start an asynchronous receive on a connected socket.

async_receive_from

Start an asynchronous receive.

async_send

Start an asynchronous send on a connected socket.

async_send_to

Start an asynchronous send.

at_mark

Determine whether the socket is at the out-of-band data mark.

available

Determine the number of bytes available for reading.

basic_raw_socket

Construct a basic_raw_socket without opening it.

Construct and open a basic_raw_socket.

Construct a basic_raw_socket, opening it and binding it to the given local endpoint.

Construct a basic_raw_socket on an existing native socket.

Move-construct a basic_raw_socket from another.

Move-construct a basic_raw_socket from a socket of another protocol type.

bind

Bind the socket to the given local endpoint.

cancel

Cancel all asynchronous operations associated with the socket.

close

Close the socket.

connect

Connect the socket to the specified endpoint.

get_io_service

Get the io_service associated with the object.

get_option

Get an option from the socket.

io_control

Perform an IO control command on the socket.

is_open

Determine whether the socket is open.

local_endpoint

Get the local endpoint of the socket.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native socket representation.

native_handle

Get the native socket representation.

native_non_blocking

Gets the non-blocking mode of the native socket implementation.

Sets the non-blocking mode of the native socket implementation.

non_blocking

Gets the non-blocking mode of the socket.

Sets the non-blocking mode of the socket.

open

Open the socket using the specified protocol.

operator=

Move-assign a basic_raw_socket from another.

Move-assign a basic_raw_socket from a socket of another protocol type.

receive

Receive some data on a connected socket.

receive_from

Receive raw data with the endpoint of the sender.

remote_endpoint

Get the remote endpoint of the socket.

send

Send some data on a connected socket.

send_to

Send raw data to the specified endpoint.

set_option

Set an option on the socket.

shutdown

Disable sends or receives on the socket.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Data Members

Name

Description

max_connections

The maximum length of the queue of pending incoming connections.

message_do_not_route

Specify that the data should not be subject to routing.

message_end_of_record

Specifies that the data marks the end of a record.

message_out_of_band

Process out-of-band data.

message_peek

Peek at incoming data without removing it from the input queue.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_raw_socket class template provides asynchronous and blocking raw-oriented socket functionality.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/generic/raw_protocol.hpp

Convenience header: boost/asio.hpp

Obtain an identifier for the type of the protocol.

int type() const;

Encapsulates the flags needed for a generic sequenced packet socket.

class seq_packet_protocol
Types

Name

Description

endpoint

The type of an endpoint.

socket

The generic socket type.

Member Functions

Name

Description

family

Obtain an identifier for the protocol family.

protocol

Obtain an identifier for the protocol.

seq_packet_protocol

Construct a protocol object for a specific address family and protocol.

Construct a generic protocol object from a specific protocol.

type

Obtain an identifier for the type of the protocol.

Friends

Name

Description

operator!=

Compare two protocols for inequality.

operator==

Compare two protocols for equality.

The generic::seq_packet_protocol class contains flags necessary for seq_packet-oriented sockets of any address family and protocol.

Examples

Constructing using a native address family and socket protocol:

seq_packet_protocol p(AF_INET, IPPROTO_SCTP);
Thread Safety

Distinct objects: Safe.

Shared objects: Safe.

Requirements

Header: boost/asio/generic/seq_packet_protocol.hpp

Convenience header: boost/asio.hpp

The type of an endpoint.

typedef basic_endpoint< seq_packet_protocol > endpoint;
Types

Name

Description

data_type

The type of the endpoint structure. This type is dependent on the underlying implementation of the socket layer.

protocol_type

The protocol type associated with the endpoint.

Member Functions

Name

Description

basic_endpoint

Default constructor.

Construct an endpoint from the specified socket address.

Construct an endpoint from the specific endpoint type.

Copy constructor.

capacity

Get the capacity of the endpoint in the native type.

data

Get the underlying endpoint in the native type.

operator=

Assign from another endpoint.

protocol

The protocol associated with the endpoint.

resize

Set the underlying size of the endpoint in the native type.

size

Get the underlying size of the endpoint in the native type.

Friends

Name

Description

operator!=

Compare two endpoints for inequality.

operator<

Compare endpoints for ordering.

operator<=

Compare endpoints for ordering.

operator==

Compare two endpoints for equality.

operator>

Compare endpoints for ordering.

operator>=

Compare endpoints for ordering.

The generic::basic_endpoint class template describes an endpoint that may be associated with any socket type.

Remarks

The socket types sockaddr type must be able to fit into a sockaddr_storage structure.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/generic/seq_packet_protocol.hpp

Convenience header: boost/asio.hpp

Obtain an identifier for the protocol family.

int family() const;

Compare two protocols for inequality.

friend bool operator!=(
    const seq_packet_protocol & p1,
    const seq_packet_protocol & p2);
Requirements

Header: boost/asio/generic/seq_packet_protocol.hpp

Convenience header: boost/asio.hpp

Compare two protocols for equality.

friend bool operator==(
    const seq_packet_protocol & p1,
    const seq_packet_protocol & p2);
Requirements

Header: boost/asio/generic/seq_packet_protocol.hpp

Convenience header: boost/asio.hpp

Obtain an identifier for the protocol.

int protocol() const;

Construct a protocol object for a specific address family and protocol.

seq_packet_protocol(
    int address_family,
    int socket_protocol);
  » more...

Construct a generic protocol object from a specific protocol.

template<
    typename Protocol>
seq_packet_protocol(
    const Protocol & source_protocol);
  » more...

Construct a protocol object for a specific address family and protocol.

seq_packet_protocol(
    int address_family,
    int socket_protocol);

Construct a generic protocol object from a specific protocol.

template<
    typename Protocol>
seq_packet_protocol(
    const Protocol & source_protocol);
Exceptions

@c

bad_cast Thrown if the source protocol is not based around sequenced packets.

The generic socket type.

typedef basic_seq_packet_socket< seq_packet_protocol > socket;
Types

Name

Description

broadcast

Socket option to permit sending of broadcast messages.

bytes_readable

IO control command to get the amount of data that can be read without blocking.

debug

Socket option to enable socket-level debugging.

do_not_route

Socket option to prevent routing, use local interfaces only.

enable_connection_aborted

Socket option to report aborted connections on accept.

endpoint_type

The endpoint type.

implementation_type

The underlying implementation type of I/O object.

keep_alive

Socket option to send keep-alives.

linger

Socket option to specify whether the socket lingers on close if unsent data is present.

lowest_layer_type

A basic_socket is always the lowest layer.

message_flags

Bitmask type for flags that can be passed to send and receive operations.

native_handle_type

The native representation of a socket.

native_type

(Deprecated: Use native_handle_type.) The native representation of a socket.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

protocol_type

The protocol type.

receive_buffer_size

Socket option for the receive buffer size of a socket.

receive_low_watermark

Socket option for the receive low watermark.

reuse_address

Socket option to allow the socket to be bound to an address that is already in use.

send_buffer_size

Socket option for the send buffer size of a socket.

send_low_watermark

Socket option for the send low watermark.

service_type

The type of the service that will be used to provide I/O operations.

shutdown_type

Different ways a socket may be shutdown.

Member Functions

Name

Description

assign

Assign an existing native socket to the socket.

async_connect

Start an asynchronous connect.

async_receive

Start an asynchronous receive.

async_send

Start an asynchronous send.

at_mark

Determine whether the socket is at the out-of-band data mark.

available

Determine the number of bytes available for reading.

basic_seq_packet_socket

Construct a basic_seq_packet_socket without opening it.

Construct and open a basic_seq_packet_socket.

Construct a basic_seq_packet_socket, opening it and binding it to the given local endpoint.

Construct a basic_seq_packet_socket on an existing native socket.

Move-construct a basic_seq_packet_socket from another.

Move-construct a basic_seq_packet_socket from a socket of another protocol type.

bind

Bind the socket to the given local endpoint.

cancel

Cancel all asynchronous operations associated with the socket.

close

Close the socket.

connect

Connect the socket to the specified endpoint.

get_io_service

Get the io_service associated with the object.

get_option

Get an option from the socket.

io_control

Perform an IO control command on the socket.

is_open

Determine whether the socket is open.

local_endpoint

Get the local endpoint of the socket.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native socket representation.

native_handle

Get the native socket representation.

native_non_blocking

Gets the non-blocking mode of the native socket implementation.

Sets the non-blocking mode of the native socket implementation.

non_blocking

Gets the non-blocking mode of the socket.

Sets the non-blocking mode of the socket.

open

Open the socket using the specified protocol.

operator=

Move-assign a basic_seq_packet_socket from another.

Move-assign a basic_seq_packet_socket from a socket of another protocol type.

receive

Receive some data on the socket.

Receive some data on a connected socket.

remote_endpoint

Get the remote endpoint of the socket.

send

Send some data on the socket.

set_option

Set an option on the socket.

shutdown

Disable sends or receives on the socket.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Data Members

Name

Description

max_connections

The maximum length of the queue of pending incoming connections.

message_do_not_route

Specify that the data should not be subject to routing.

message_end_of_record

Specifies that the data marks the end of a record.

message_out_of_band

Process out-of-band data.

message_peek

Peek at incoming data without removing it from the input queue.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_seq_packet_socket class template provides asynchronous and blocking sequenced packet socket functionality.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/generic/seq_packet_protocol.hpp

Convenience header: boost/asio.hpp

Obtain an identifier for the type of the protocol.

int type() const;

Encapsulates the flags needed for a generic stream-oriented socket.

class stream_protocol
Types

Name

Description

endpoint

The type of an endpoint.

iostream

The generic socket iostream type.

socket

The generic socket type.

Member Functions

Name

Description

family

Obtain an identifier for the protocol family.

protocol

Obtain an identifier for the protocol.

stream_protocol

Construct a protocol object for a specific address family and protocol.

Construct a generic protocol object from a specific protocol.

type

Obtain an identifier for the type of the protocol.

Friends

Name

Description

operator!=

Compare two protocols for inequality.

operator==

Compare two protocols for equality.

The generic::stream_protocol class contains flags necessary for stream-oriented sockets of any address family and protocol.

Examples

Constructing using a native address family and socket protocol:

stream_protocol p(AF_INET, IPPROTO_TCP);

Constructing from a specific protocol type:

stream_protocol p(boost::asio::ip::tcp::v4());
Thread Safety

Distinct objects: Safe.

Shared objects: Safe.

Requirements

Header: boost/asio/generic/stream_protocol.hpp

Convenience header: boost/asio.hpp

The type of an endpoint.

typedef basic_endpoint< stream_protocol > endpoint;
Types

Name

Description

data_type

The type of the endpoint structure. This type is dependent on the underlying implementation of the socket layer.

protocol_type

The protocol type associated with the endpoint.

Member Functions

Name

Description

basic_endpoint

Default constructor.

Construct an endpoint from the specified socket address.

Construct an endpoint from the specific endpoint type.

Copy constructor.

capacity

Get the capacity of the endpoint in the native type.

data

Get the underlying endpoint in the native type.

operator=

Assign from another endpoint.

protocol

The protocol associated with the endpoint.

resize

Set the underlying size of the endpoint in the native type.

size

Get the underlying size of the endpoint in the native type.

Friends

Name

Description

operator!=

Compare two endpoints for inequality.

operator<

Compare endpoints for ordering.

operator<=

Compare endpoints for ordering.

operator==

Compare two endpoints for equality.

operator>

Compare endpoints for ordering.

operator>=

Compare endpoints for ordering.

The generic::basic_endpoint class template describes an endpoint that may be associated with any socket type.

Remarks

The socket types sockaddr type must be able to fit into a sockaddr_storage structure.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/generic/stream_protocol.hpp

Convenience header: boost/asio.hpp

Obtain an identifier for the protocol family.

int family() const;

The generic socket iostream type.

typedef basic_socket_iostream< stream_protocol > iostream;
Types

Name

Description

duration_type

The duration type.

endpoint_type

The endpoint type.

time_type

The time type.

Member Functions

Name

Description

basic_socket_iostream

Construct a basic_socket_iostream without establishing a connection.

Establish a connection to an endpoint corresponding to a resolver query.

close

Close the connection.

connect

Establish a connection to an endpoint corresponding to a resolver query.

error

Get the last error associated with the stream.

expires_at

Get the stream's expiry time as an absolute time.

Set the stream's expiry time as an absolute time.

expires_from_now

Get the timer's expiry time relative to now.

Set the stream's expiry time relative to now.

rdbuf

Return a pointer to the underlying streambuf.

Requirements

Header: boost/asio/generic/stream_protocol.hpp

Convenience header: boost/asio.hpp

Compare two protocols for inequality.

friend bool operator!=(
    const stream_protocol & p1,
    const stream_protocol & p2);
Requirements

Header: boost/asio/generic/stream_protocol.hpp

Convenience header: boost/asio.hpp

Compare two protocols for equality.

friend bool operator==(
    const stream_protocol & p1,
    const stream_protocol & p2);
Requirements

Header: boost/asio/generic/stream_protocol.hpp

Convenience header: boost/asio.hpp

Obtain an identifier for the protocol.

int protocol() const;

The generic socket type.

typedef basic_stream_socket< stream_protocol > socket;
Types

Name

Description

broadcast

Socket option to permit sending of broadcast messages.

bytes_readable

IO control command to get the amount of data that can be read without blocking.

debug

Socket option to enable socket-level debugging.

do_not_route

Socket option to prevent routing, use local interfaces only.

enable_connection_aborted

Socket option to report aborted connections on accept.

endpoint_type

The endpoint type.

implementation_type

The underlying implementation type of I/O object.

keep_alive

Socket option to send keep-alives.

linger

Socket option to specify whether the socket lingers on close if unsent data is present.

lowest_layer_type

A basic_socket is always the lowest layer.

message_flags

Bitmask type for flags that can be passed to send and receive operations.

native_handle_type

The native representation of a socket.

native_type

(Deprecated: Use native_handle_type.) The native representation of a socket.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

protocol_type

The protocol type.

receive_buffer_size

Socket option for the receive buffer size of a socket.

receive_low_watermark

Socket option for the receive low watermark.

reuse_address

Socket option to allow the socket to be bound to an address that is already in use.

send_buffer_size

Socket option for the send buffer size of a socket.

send_low_watermark

Socket option for the send low watermark.

service_type

The type of the service that will be used to provide I/O operations.

shutdown_type

Different ways a socket may be shutdown.

Member Functions

Name

Description

assign

Assign an existing native socket to the socket.

async_connect

Start an asynchronous connect.

async_read_some

Start an asynchronous read.

async_receive

Start an asynchronous receive.

async_send

Start an asynchronous send.

async_write_some

Start an asynchronous write.

at_mark

Determine whether the socket is at the out-of-band data mark.

available

Determine the number of bytes available for reading.

basic_stream_socket

Construct a basic_stream_socket without opening it.

Construct and open a basic_stream_socket.

Construct a basic_stream_socket, opening it and binding it to the given local endpoint.

Construct a basic_stream_socket on an existing native socket.

Move-construct a basic_stream_socket from another.

Move-construct a basic_stream_socket from a socket of another protocol type.

bind

Bind the socket to the given local endpoint.

cancel

Cancel all asynchronous operations associated with the socket.

close

Close the socket.

connect

Connect the socket to the specified endpoint.

get_io_service

Get the io_service associated with the object.

get_option

Get an option from the socket.

io_control

Perform an IO control command on the socket.

is_open

Determine whether the socket is open.

local_endpoint

Get the local endpoint of the socket.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native socket representation.

native_handle

Get the native socket representation.

native_non_blocking

Gets the non-blocking mode of the native socket implementation.

Sets the non-blocking mode of the native socket implementation.

non_blocking

Gets the non-blocking mode of the socket.

Sets the non-blocking mode of the socket.

open

Open the socket using the specified protocol.

operator=

Move-assign a basic_stream_socket from another.

Move-assign a basic_stream_socket from a socket of another protocol type.

read_some

Read some data from the socket.

receive

Receive some data on the socket.

Receive some data on a connected socket.

remote_endpoint

Get the remote endpoint of the socket.

send

Send some data on the socket.

set_option

Set an option on the socket.

shutdown

Disable sends or receives on the socket.

write_some

Write some data to the socket.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Data Members

Name

Description

max_connections

The maximum length of the queue of pending incoming connections.

message_do_not_route

Specify that the data should not be subject to routing.

message_end_of_record

Specifies that the data marks the end of a record.

message_out_of_band

Process out-of-band data.

message_peek

Peek at incoming data without removing it from the input queue.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_stream_socket class template provides asynchronous and blocking stream-oriented socket functionality.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/generic/stream_protocol.hpp

Convenience header: boost/asio.hpp

Construct a protocol object for a specific address family and protocol.

stream_protocol(
    int address_family,
    int socket_protocol);
  » more...

Construct a generic protocol object from a specific protocol.

template<
    typename Protocol>
stream_protocol(
    const Protocol & source_protocol);
  » more...

Construct a protocol object for a specific address family and protocol.

stream_protocol(
    int address_family,
    int socket_protocol);

Construct a generic protocol object from a specific protocol.

template<
    typename Protocol>
stream_protocol(
    const Protocol & source_protocol);
Exceptions

@c

bad_cast Thrown if the source protocol is not stream-oriented.

Obtain an identifier for the type of the protocol.

int type() const;

Default handler type traits provided for all handlers.

template<
    typename Handler,
    typename Signature>
struct handler_type
Types

Name

Description

type

The handler type for the specific signature.

The handler_type traits class is used for determining the concrete handler type to be used for an asynchronous operation. It allows the handler type to be determined at the point where the specific completion handler signature is known.

This template may be specialised for user-defined handler types.

Requirements

Header: boost/asio/handler_type.hpp

Convenience header: boost/asio.hpp

The handler type for the specific signature.

typedef Handler type;
Requirements

Header: boost/asio/handler_type.hpp

Convenience header: boost/asio.hpp

template<
    typename Service>
bool has_service(
    io_service & ios);

This function is used to determine whether the io_service contains a service object corresponding to the given service type.

Parameters

ios

The io_service object that owns the service.

Return Value

A boolean indicating whether the io_service contains the service.

Requirements

Header: boost/asio/io_service.hpp

Convenience header: boost/asio.hpp

Typedef for a timer based on the high resolution clock.

typedef basic_waitable_timer< chrono::high_resolution_clock > high_resolution_timer;
Types

Name

Description

clock_type

The clock type.

duration

The duration type of the clock.

implementation_type

The underlying implementation type of I/O object.

service_type

The type of the service that will be used to provide I/O operations.

time_point

The time point type of the clock.

traits_type

The wait traits type.

Member Functions

Name

Description

async_wait

Start an asynchronous wait on the timer.

basic_waitable_timer

Constructor.

Constructor to set a particular expiry time as an absolute time.

Constructor to set a particular expiry time relative to now.

cancel

Cancel any asynchronous operations that are waiting on the timer.

cancel_one

Cancels one asynchronous operation that is waiting on the timer.

expires_at

Get the timer's expiry time as an absolute time.

Set the timer's expiry time as an absolute time.

expires_from_now

Get the timer's expiry time relative to now.

Set the timer's expiry time relative to now.

get_io_service

Get the io_service associated with the object.

wait

Perform a blocking wait on the timer.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_waitable_timer class template provides the ability to perform a blocking or asynchronous wait for a timer to expire.

A waitable timer is always in one of two states: "expired" or "not expired". If the wait() or async_wait() function is called on an expired timer, the wait operation will complete immediately.

Most applications will use one of the steady_timer, system_timer or high_resolution_timer typedefs.

Remarks

This waitable timer functionality is for use with the C++11 standard library's <chrono> facility, or with the Boost.Chrono library.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Examples

Performing a blocking wait (C++11):

// Construct a timer without setting an expiry time.
boost::asio::steady_timer timer(io_service);

// Set an expiry time relative to now.
timer.expires_from_now(std::chrono::seconds(5));

// Wait for the timer to expire.
timer.wait();

Performing an asynchronous wait (C++11):

void handler(const boost::system::error_code& error)
{
  if (!error)
  {
    // Timer expired.
  }
}

...

// Construct a timer with an absolute expiry time.
boost::asio::steady_timer timer(io_service,
    std::chrono::steady_clock::now() + std::chrono::seconds(60));

// Start an asynchronous wait.
timer.async_wait(handler);
Changing an active waitable timer's expiry time

Changing the expiry time of a timer while there are pending asynchronous waits causes those wait operations to be cancelled. To ensure that the action associated with the timer is performed only once, use something like this: used:

void on_some_event()
{
  if (my_timer.expires_from_now(seconds(5)) > 0)
  {
    // We managed to cancel the timer. Start new asynchronous wait.
    my_timer.async_wait(on_timeout);
  }
  else
  {
    // Too late, timer has already expired!
  }
}

void on_timeout(const boost::system::error_code& e)
{
  if (e != boost::asio::error::operation_aborted)
  {
    // Timer was not cancelled, take necessary action.
  }
}
  • The boost::asio::basic_waitable_timer::expires_from_now() function cancels any pending asynchronous waits, and returns the number of asynchronous waits that were cancelled. If it returns 0 then you were too late and the wait handler has already been executed, or will soon be executed. If it returns 1 then the wait handler was successfully cancelled.
  • If a wait handler is cancelled, the boost::system::error_code passed to it contains the value boost::asio::error::operation_aborted.

This typedef uses the C++11 <chrono> standard library facility, if available. Otherwise, it may use the Boost.Chrono library. To explicitly utilise Boost.Chrono, use the basic_waitable_timer template directly:

typedef basic_waitable_timer<boost::chrono::high_resolution_clock> timer;
Requirements

Header: boost/asio/high_resolution_timer.hpp

Convenience header: None

Exception thrown when trying to add a service object to an io_service where the service has a different owner.

class invalid_service_owner
Member Functions

Name

Description

invalid_service_owner

Requirements

Header: boost/asio/io_service.hpp

Convenience header: boost/asio.hpp

Provides core I/O functionality.

class io_service :
  noncopyable
Types

Name

Description

id

Class used to uniquely identify a service.

service

Base class for all io_service services.

strand

Provides serialised handler execution.

work

Class to inform the io_service when it has work to do.

fork_event

Fork-related event notifications.

Member Functions

Name

Description

dispatch

Request the io_service to invoke the given handler.

io_service

Constructor.

notify_fork

Notify the io_service of a fork-related event.

poll

Run the io_service object's event processing loop to execute ready handlers.

poll_one

Run the io_service object's event processing loop to execute one ready handler.

post

Request the io_service to invoke the given handler and return immediately.

reset

Reset the io_service in preparation for a subsequent run() invocation.

run

Run the io_service object's event processing loop.

run_one

Run the io_service object's event processing loop to execute at most one handler.

stop

Stop the io_service object's event processing loop.

stopped

Determine whether the io_service object has been stopped.

wrap

Create a new handler that automatically dispatches the wrapped handler on the io_service.

~io_service

Destructor.

Friends

Name

Description

add_service

Add a service object to the io_service.

has_service

Determine if an io_service contains a specified service type.

use_service

Obtain the service object corresponding to the given type.

The io_service class provides the core I/O functionality for users of the asynchronous I/O objects, including:

  • boost::asio::ip::tcp::socket
  • boost::asio::ip::tcp::acceptor
  • boost::asio::ip::udp::socket
  • deadline_timer.

The io_service class also includes facilities intended for developers of custom asynchronous services.

Thread Safety

Distinct objects: Safe.

Shared objects: Safe, with the specific exceptions of the reset() and notify_fork() functions. Calling reset() while there are unfinished run(), run_one(), poll() or poll_one() calls results in undefined behaviour. The notify_fork() function should not be called while any io_service function, or any function on an I/O object that is associated with the io_service, is being called in another thread.

Synchronous and asynchronous operations

Synchronous operations on I/O objects implicitly run the io_service object for an individual operation. The io_service functions run(), run_one(), poll() or poll_one() must be called for the io_service to perform asynchronous operations on behalf of a C++ program. Notification that an asynchronous operation has completed is delivered by invocation of the associated handler. Handlers are invoked only by a thread that is currently calling any overload of run(), run_one(), poll() or poll_one() for the io_service.

Effect of exceptions thrown from handlers

If an exception is thrown from a handler, the exception is allowed to propagate through the throwing thread's invocation of run(), run_one(), poll() or poll_one(). No other threads that are calling any of these functions are affected. It is then the responsibility of the application to catch the exception.

After the exception has been caught, the run(), run_one(), poll() or poll_one() call may be restarted without the need for an intervening call to reset(). This allows the thread to rejoin the io_service object's thread pool without impacting any other threads in the pool.

For example:

boost::asio::io_service io_service;
...
for (;;)
{
  try
  {
    io_service.run();
    break; // run() exited normally
  }
  catch (my_exception& e)
  {
    // Deal with exception as appropriate.
  }
}
Stopping the io_service from running out of work

Some applications may need to prevent an io_service object's run() call from returning when there is no more work to do. For example, the io_service may be being run in a background thread that is launched prior to the application's asynchronous operations. The run() call may be kept running by creating an object of type io_service::work:

boost::asio::io_service io_service;
boost::asio::io_service::work work(io_service);
...

To effect a shutdown, the application will then need to call the io_service object's stop() member function. This will cause the io_service run() call to return as soon as possible, abandoning unfinished operations and without permitting ready handlers to be dispatched.

Alternatively, if the application requires that all operations and handlers be allowed to finish normally, the work object may be explicitly destroyed.

boost::asio::io_service io_service;
auto_ptr<boost::asio::io_service::work> work(
    new boost::asio::io_service::work(io_service));
...
work.reset(); // Allow run() to exit. 
The io_service class and I/O services

Class io_service implements an extensible, type-safe, polymorphic set of I/O services, indexed by service type. An object of class io_service must be initialised before I/O objects such as sockets, resolvers and timers can be used. These I/O objects are distinguished by having constructors that accept an io_service& parameter.

I/O services exist to manage the logical interface to the operating system on behalf of the I/O objects. In particular, there are resources that are shared across a class of I/O objects. For example, timers may be implemented in terms of a single timer queue. The I/O services manage these shared resources.

Access to the services of an io_service is via three function templates, use_service(), add_service() and has_service().

In a call to use_service<Service>(), the type argument chooses a service, making available all members of the named type. If Service is not present in an io_service, an object of type Service is created and added to the io_service. A C++ program can check if an io_service implements a particular service with the function template has_service<Service>().

Service objects may be explicitly added to an io_service using the function template add_service<Service>(). If the Service is already present, the service_already_exists exception is thrown. If the owner of the service is not the same object as the io_service parameter, the invalid_service_owner exception is thrown.

Once a service reference is obtained from an io_service object by calling use_service(), that reference remains usable as long as the owning io_service object exists.

All I/O service implementations have io_service::service as a public base class. Custom I/O services may be implemented by deriving from this class and then added to an io_service using the facilities described above.

Requirements

Header: boost/asio/io_service.hpp

Convenience header: boost/asio.hpp

Add a service object to the io_service.

template<
    typename Service>
friend void add_service(
    io_service & ios,
    Service * svc);

This function is used to add a service to the io_service.

Parameters

ios

The io_service object that owns the service.

svc

The service object. On success, ownership of the service object is transferred to the io_service. When the io_service object is destroyed, it will destroy the service object by performing:

delete static_cast<io_service::service*>(svc)

Exceptions

boost::asio::service_already_exists

Thrown if a service of the given type is already present in the io_service.

boost::asio::invalid_service_owner

Thrown if the service's owning io_service is not the io_service object specified by the ios parameter.

Requirements

Header: boost/asio/io_service.hpp

Convenience header: boost/asio.hpp

Request the io_service to invoke the given handler.

template<
    typename CompletionHandler>
void-or-deduced dispatch(
    CompletionHandler handler);

This function is used to ask the io_service to execute the given handler.

The io_service guarantees that the handler will only be called in a thread in which the run(), run_one(), poll() or poll_one() member functions is currently being invoked. The handler may be executed inside this function if the guarantee can be met.

Parameters

handler

The handler to be called. The io_service will make a copy of the handler object as required. The function signature of the handler must be:

void handler();

Remarks

This function throws an exception only if:

  • the handler's asio_handler_allocate function; or
  • the handler's copy constructor

throws an exception.

Fork-related event notifications.

enum fork_event

Values

fork_prepare

Notify the io_service that the process is about to fork.

fork_parent

Notify the io_service that the process has forked and is the parent.

fork_child

Notify the io_service that the process has forked and is the child.

Determine if an io_service contains a specified service type.

template<
    typename Service>
friend bool has_service(
    io_service & ios);

This function is used to determine whether the io_service contains a service object corresponding to the given service type.

Parameters

ios

The io_service object that owns the service.

Return Value

A boolean indicating whether the io_service contains the service.

Requirements

Header: boost/asio/io_service.hpp

Convenience header: boost/asio.hpp

Constructor.

io_service();
  » more...

explicit io_service(
    std::size_t concurrency_hint);
  » more...

Constructor.

io_service();

Constructor.

io_service(
    std::size_t concurrency_hint);

Construct with a hint about the required level of concurrency.

Parameters

concurrency_hint

A suggestion to the implementation on how many threads it should allow to run simultaneously.

Notify the io_service of a fork-related event.

void notify_fork(
    boost::asio::io_service::fork_event event);

This function is used to inform the io_service that the process is about to fork, or has just forked. This allows the io_service, and the services it contains, to perform any necessary housekeeping to ensure correct operation following a fork.

This function must not be called while any other io_service function, or any function on an I/O object associated with the io_service, is being called in another thread. It is, however, safe to call this function from within a completion handler, provided no other thread is accessing the io_service.

Parameters

event

A fork-related event.

Exceptions

boost::system::system_error

Thrown on failure. If the notification fails the io_service object should no longer be used and should be destroyed.

Example

The following code illustrates how to incorporate the notify_fork() function:

my_io_service.notify_fork(boost::asio::io_service::fork_prepare);
if (fork() == 0)
{
  // This is the child process.
  my_io_service.notify_fork(boost::asio::io_service::fork_child);
}
else
{
  // This is the parent process.
  my_io_service.notify_fork(boost::asio::io_service::fork_parent);
}
Remarks

For each service object svc in the io_service set, performs svc->fork_service();. When processing the fork_prepare event, services are visited in reverse order of the beginning of service object lifetime. Otherwise, services are visited in order of the beginning of service object lifetime.

Run the io_service object's event processing loop to execute ready handlers.

std::size_t poll();
  » more...

std::size_t poll(
    boost::system::error_code & ec);
  » more...

Run the io_service object's event processing loop to execute ready handlers.

std::size_t poll();

The poll() function runs handlers that are ready to run, without blocking, until the io_service has been stopped or there are no more ready handlers.

Return Value

The number of handlers that were executed.

Exceptions

boost::system::system_error

Thrown on failure.

Run the io_service object's event processing loop to execute ready handlers.

std::size_t poll(
    boost::system::error_code & ec);

The poll() function runs handlers that are ready to run, without blocking, until the io_service has been stopped or there are no more ready handlers.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

The number of handlers that were executed.

Run the io_service object's event processing loop to execute one ready handler.

std::size_t poll_one();
  » more...

std::size_t poll_one(
    boost::system::error_code & ec);
  » more...

Run the io_service object's event processing loop to execute one ready handler.

std::size_t poll_one();

The poll_one() function runs at most one handler that is ready to run, without blocking.

Return Value

The number of handlers that were executed.

Exceptions

boost::system::system_error

Thrown on failure.

Run the io_service object's event processing loop to execute one ready handler.

std::size_t poll_one(
    boost::system::error_code & ec);

The poll_one() function runs at most one handler that is ready to run, without blocking.

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

The number of handlers that were executed.

Request the io_service to invoke the given handler and return immediately.

template<
    typename CompletionHandler>
void-or-deduced post(
    CompletionHandler handler);

This function is used to ask the io_service to execute the given handler, but without allowing the io_service to call the handler from inside this function.

The io_service guarantees that the handler will only be called in a thread in which the run(), run_one(), poll() or poll_one() member functions is currently being invoked.

Parameters

handler

The handler to be called. The io_service will make a copy of the handler object as required. The function signature of the handler must be:

void handler();

Remarks

This function throws an exception only if:

  • the handler's asio_handler_allocate function; or
  • the handler's copy constructor

throws an exception.

Reset the io_service in preparation for a subsequent run() invocation.

void reset();

This function must be called prior to any second or later set of invocations of the run(), run_one(), poll() or poll_one() functions when a previous invocation of these functions returned due to the io_service being stopped or running out of work. After a call to reset(), the io_service object's stopped() function will return false.

This function must not be called while there are any unfinished calls to the run(), run_one(), poll() or poll_one() functions.

Run the io_service object's event processing loop.

std::size_t run();
  » more...

std::size_t run(
    boost::system::error_code & ec);
  » more...

Run the io_service object's event processing loop.

std::size_t run();

The run() function blocks until all work has finished and there are no more handlers to be dispatched, or until the io_service has been stopped.

Multiple threads may call the run() function to set up a pool of threads from which the io_service may execute handlers. All threads that are waiting in the pool are equivalent and the io_service may choose any one of them to invoke a handler.

A normal exit from the run() function implies that the io_service object is stopped (the stopped() function returns true). Subsequent calls to run(), run_one(), poll() or poll_one() will return immediately unless there is a prior call to reset().

Return Value

The number of handlers that were executed.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

The run() function must not be called from a thread that is currently calling one of run(), run_one(), poll() or poll_one() on the same io_service object.

The poll() function may also be used to dispatch ready handlers, but without blocking.

Run the io_service object's event processing loop.

std::size_t run(
    boost::system::error_code & ec);

The run() function blocks until all work has finished and there are no more handlers to be dispatched, or until the io_service has been stopped.

Multiple threads may call the run() function to set up a pool of threads from which the io_service may execute handlers. All threads that are waiting in the pool are equivalent and the io_service may choose any one of them to invoke a handler.

A normal exit from the run() function implies that the io_service object is stopped (the stopped() function returns true). Subsequent calls to run(), run_one(), poll() or poll_one() will return immediately unless there is a prior call to reset().

Parameters

ec

Set to indicate what error occurred, if any.

Return Value

The number of handlers that were executed.

Remarks

The run() function must not be called from a thread that is currently calling one of run(), run_one(), poll() or poll_one() on the same io_service object.

The poll() function may also be used to dispatch ready handlers, but without blocking.

Run the io_service object's event processing loop to execute at most one handler.

std::size_t run_one();
  » more...

std::size_t run_one(
    boost::system::error_code & ec);
  » more...

Run the io_service object's event processing loop to execute at most one handler.

std::size_t run_one();

The run_one() function blocks until one handler has been dispatched, or until the io_service has been stopped.

Return Value

The number of handlers that were executed. A zero return value implies that the io_service object is stopped (the stopped() function returns true). Subsequent calls to run(), run_one(), poll() or poll_one() will return immediately unless there is a prior call to reset().

Exceptions

boost::system::system_error

Thrown on failure.

Run the io_service object's event processing loop to execute at most one handler.

std::size_t run_one(
    boost::system::error_code & ec);

The run_one() function blocks until one handler has been dispatched, or until the io_service has been stopped.

Return Value

The number of handlers that were executed. A zero return value implies that the io_service object is stopped (the stopped() function returns true). Subsequent calls to run(), run_one(), poll() or poll_one() will return immediately unless there is a prior call to reset().

The number of handlers that were executed.

Stop the io_service object's event processing loop.

void stop();

This function does not block, but instead simply signals the io_service to stop. All invocations of its run() or run_one() member functions should return as soon as possible. Subsequent calls to run(), run_one(), poll() or poll_one() will return immediately until reset() is called.

Determine whether the io_service object has been stopped.

bool stopped() const;

This function is used to determine whether an io_service object has been stopped, either through an explicit call to stop(), or due to running out of work. When an io_service object is stopped, calls to run(), run_one(), poll() or poll_one() will return immediately without invoking any handlers.

Return Value

true if the io_service object is stopped, otherwise false.

Obtain the service object corresponding to the given type.

template<
    typename Service>
friend Service & use_service(
    io_service & ios);

This function is used to locate a service object that corresponds to the given service type. If there is no existing implementation of the service, then the io_service will create a new instance of the service.

Parameters

ios

The io_service object that owns the service.

Return Value

The service interface implementing the specified service type. Ownership of the service interface is not transferred to the caller.

Requirements

Header: boost/asio/io_service.hpp

Convenience header: boost/asio.hpp

Create a new handler that automatically dispatches the wrapped handler on the io_service.

template<
    typename Handler>
unspecified wrap(
    Handler handler);

This function is used to create a new handler function object that, when invoked, will automatically pass the wrapped handler to the io_service object's dispatch function.

Parameters

handler

The handler to be wrapped. The io_service will make a copy of the handler object as required. The function signature of the handler must be:

void handler(A1 a1, ... An an);

Return Value

A function object that, when invoked, passes the wrapped handler to the io_service object's dispatch function. Given a function object with the signature:

R f(A1 a1, ... An an);

If this function object is passed to the wrap function like so:

io_service.wrap(f);

then the return value is a function object with the signature

void g(A1 a1, ... An an);

that, when invoked, executes code equivalent to:

io_service.dispatch(boost::bind(f, a1, ... an));

Destructor.

~io_service();

On destruction, the io_service performs the following sequence of operations:

  • For each service object svc in the io_service set, in reverse order of the beginning of service object lifetime, performs svc->shutdown_service().
  • Uninvoked handler objects that were scheduled for deferred invocation on the io_service, or any associated strand, are destroyed.
  • For each service object svc in the io_service set, in reverse order of the beginning of service object lifetime, performs delete static_cast<io_service::service*>(svc).
Remarks

The destruction sequence described above permits programs to simplify their resource management by using shared_ptr<>. Where an object's lifetime is tied to the lifetime of a connection (or some other sequence of asynchronous operations), a shared_ptr to the object would be bound into the handlers for all asynchronous operations associated with it. This works as follows:

  • When a single connection ends, all associated asynchronous operations complete. The corresponding handler objects are destroyed, and all shared_ptr references to the objects are destroyed.
  • To shut down the whole program, the io_service function stop() is called to terminate any run() calls as soon as possible. The io_service destructor defined above destroys all handlers, causing all shared_ptr references to all connection objects to be destroyed.

Class used to uniquely identify a service.

class id :
  noncopyable
Member Functions

Name

Description

id

Constructor.

Requirements

Header: boost/asio/io_service.hpp

Convenience header: boost/asio.hpp

Constructor.

id();

Base class for all io_service services.

class service :
  noncopyable
Member Functions

Name

Description

get_io_service

Get the io_service object that owns the service.

Protected Member Functions

Name

Description

service

Constructor.

~service

Destructor.

Private Member Functions

Name

Description

fork_service

Handle notification of a fork-related event to perform any necessary housekeeping.

shutdown_service

Destroy all user-defined handler objects owned by the service.

Requirements

Header: boost/asio/io_service.hpp

Convenience header: boost/asio.hpp

Get the io_service object that owns the service.

boost::asio::io_service & get_io_service();

Constructor.

service(
    boost::asio::io_service & owner);
Parameters

owner

The io_service object that owns the service.

Destructor.

virtual ~service();

Handle notification of a fork-related event to perform any necessary housekeeping.

virtual void fork_service(
    boost::asio::io_service::fork_event event);

This function is not a pure virtual so that services only have to implement it if necessary. The default implementation does nothing.

Destroy all user-defined handler objects owned by the service.

void shutdown_service();

Provides serialised handler execution.

class strand
Member Functions

Name

Description

dispatch

Request the strand to invoke the given handler.

get_io_service

Get the io_service associated with the strand.

post

Request the strand to invoke the given handler and return immediately.

running_in_this_thread

Determine whether the strand is running in the current thread.

strand

Constructor.

wrap

Create a new handler that automatically dispatches the wrapped handler on the strand.

~strand

Destructor.

The io_service::strand class provides the ability to post and dispatch handlers with the guarantee that none of those handlers will execute concurrently.

Order of handler invocation

Given:

  • a strand object s
  • an object a meeting completion handler requirements
  • an object a1 which is an arbitrary copy of a made by the implementation
  • an object b meeting completion handler requirements
  • an object b1 which is an arbitrary copy of b made by the implementation

if any of the following conditions are true:

  • s.post(a) happens-before s.post(b)
  • s.post(a) happens-before s.dispatch(b), where the latter is performed outside the strand
  • s.dispatch(a) happens-before s.post(b), where the former is performed outside the strand
  • s.dispatch(a) happens-before s.dispatch(b), where both are performed outside the strand

then asio_handler_invoke(a1, &a1) happens-before asio_handler_invoke(b1, &b1).

Note that in the following case:

async_op_1(..., s.wrap(a));
async_op_2(..., s.wrap(b));

the completion of the first async operation will perform s.dispatch(a), and the second will perform s.dispatch(b), but the order in which those are performed is unspecified. That is, you cannot state whether one happens-before the other. Therefore none of the above conditions are met and no ordering guarantee is made.

Remarks

The implementation makes no guarantee that handlers posted or dispatched through different strand objects will be invoked concurrently.

Thread Safety

Distinct objects: Safe.

Shared objects: Safe.

Requirements

Header: boost/asio/strand.hpp

Convenience header: boost/asio.hpp

Request the strand to invoke the given handler.

template<
    typename CompletionHandler>
void-or-deduced dispatch(
    CompletionHandler handler);

This function is used to ask the strand to execute the given handler.

The strand object guarantees that handlers posted or dispatched through the strand will not be executed concurrently. The handler may be executed inside this function if the guarantee can be met. If this function is called from within a handler that was posted or dispatched through the same strand, then the new handler will be executed immediately.

The strand's guarantee is in addition to the guarantee provided by the underlying io_service. The io_service guarantees that the handler will only be called in a thread in which the io_service's run member function is currently being invoked.

Parameters

handler

The handler to be called. The strand will make a copy of the handler object as required. The function signature of the handler must be:

void handler();

Get the io_service associated with the strand.

boost::asio::io_service & get_io_service();

This function may be used to obtain the io_service object that the strand uses to dispatch handlers for asynchronous operations.

Return Value

A reference to the io_service object that the strand will use to dispatch handlers. Ownership is not transferred to the caller.

Request the strand to invoke the given handler and return immediately.

template<
    typename CompletionHandler>
void-or-deduced post(
    CompletionHandler handler);

This function is used to ask the strand to execute the given handler, but without allowing the strand to call the handler from inside this function.

The strand object guarantees that handlers posted or dispatched through the strand will not be executed concurrently. The strand's guarantee is in addition to the guarantee provided by the underlying io_service. The io_service guarantees that the handler will only be called in a thread in which the io_service's run member function is currently being invoked.

Parameters

handler

The handler to be called. The strand will make a copy of the handler object as required. The function signature of the handler must be:

void handler();

Determine whether the strand is running in the current thread.

bool running_in_this_thread() const;
Return Value

true if the current thread is executing a handler that was submitted to the strand using post(), dispatch() or wrap(). Otherwise returns false.

Constructor.

strand(
    boost::asio::io_service & io_service);

Constructs the strand.

Parameters

io_service

The io_service object that the strand will use to dispatch handlers that are ready to be run.

Create a new handler that automatically dispatches the wrapped handler on the strand.

template<
    typename Handler>
unspecified wrap(
    Handler handler);

This function is used to create a new handler function object that, when invoked, will automatically pass the wrapped handler to the strand's dispatch function.

Parameters

handler

The handler to be wrapped. The strand will make a copy of the handler object as required. The function signature of the handler must be:

void handler(A1 a1, ... An an);

Return Value

A function object that, when invoked, passes the wrapped handler to the strand's dispatch function. Given a function object with the signature:

R f(A1 a1, ... An an);

If this function object is passed to the wrap function like so:

strand.wrap(f);

then the return value is a function object with the signature

void g(A1 a1, ... An an);

that, when invoked, executes code equivalent to:

strand.dispatch(boost::bind(f, a1, ... an));

Destructor.

~strand();

Destroys a strand.

Handlers posted through the strand that have not yet been invoked will still be dispatched in a way that meets the guarantee of non-concurrency.

Class to inform the io_service when it has work to do.

class work
Member Functions

Name

Description

get_io_service

Get the io_service associated with the work.

work

Constructor notifies the io_service that work is starting.

Copy constructor notifies the io_service that work is starting.

~work

Destructor notifies the io_service that the work is complete.

The work class is used to inform the io_service when work starts and finishes. This ensures that the io_service object's run() function will not exit while work is underway, and that it does exit when there is no unfinished work remaining.

The work class is copy-constructible so that it may be used as a data member in a handler class. It is not assignable.

Requirements

Header: boost/asio/io_service.hpp

Convenience header: boost/asio.hpp

Get the io_service associated with the work.

boost::asio::io_service & get_io_service();

Constructor notifies the io_service that work is starting.

explicit work(
    boost::asio::io_service & io_service);
  » more...

Copy constructor notifies the io_service that work is starting.

work(
    const work & other);
  » more...

Constructor notifies the io_service that work is starting.

work(
    boost::asio::io_service & io_service);

The constructor is used to inform the io_service that some work has begun. This ensures that the io_service object's run() function will not exit while the work is underway.

Copy constructor notifies the io_service that work is starting.

work(
    const work & other);

The constructor is used to inform the io_service that some work has begun. This ensures that the io_service object's run() function will not exit while the work is underway.

Destructor notifies the io_service that the work is complete.

~work();

The destructor is used to inform the io_service that some work has finished. Once the count of unfinished work reaches zero, the io_service object's run() function is permitted to exit.

Implements version-independent IP addresses.

class address
Member Functions

Name

Description

address

Default constructor.

Construct an address from an IPv4 address.

Construct an address from an IPv6 address.

Copy constructor.

from_string

Create an address from an IPv4 address string in dotted decimal form, or from an IPv6 address in hexadecimal notation.

is_loopback

Determine whether the address is a loopback address.

is_multicast

Determine whether the address is a multicast address.

is_unspecified

Determine whether the address is unspecified.

is_v4

Get whether the address is an IP version 4 address.

is_v6

Get whether the address is an IP version 6 address.

operator=

Assign from another address.

Assign from an IPv4 address.

Assign from an IPv6 address.

to_string

Get the address as a string in dotted decimal format.

to_v4

Get the address as an IP version 4 address.

to_v6

Get the address as an IP version 6 address.

Friends

Name

Description

operator!=

Compare two addresses for inequality.

operator<

Compare addresses for ordering.

operator<=

Compare addresses for ordering.

operator==

Compare two addresses for equality.

operator>

Compare addresses for ordering.

operator>=

Compare addresses for ordering.

Related Functions

Name

Description

operator<<

Output an address as a string.

The ip::address class provides the ability to use either IP version 4 or version 6 addresses.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/ip/address.hpp

Convenience header: boost/asio.hpp

Default constructor.

address();
  » more...

Construct an address from an IPv4 address.

address(
    const boost::asio::ip::address_v4 & ipv4_address);
  » more...

Construct an address from an IPv6 address.

address(
    const boost::asio::ip::address_v6 & ipv6_address);
  » more...

Copy constructor.

address(
    const address & other);
  » more...

Default constructor.

address();

Construct an address from an IPv4 address.

address(
    const boost::asio::ip::address_v4 & ipv4_address);

Construct an address from an IPv6 address.

address(
    const boost::asio::ip::address_v6 & ipv6_address);

Copy constructor.

address(
    const address & other);

Create an address from an IPv4 address string in dotted decimal form, or from an IPv6 address in hexadecimal notation.

static address from_string(
    const char * str);
  » more...

static address from_string(
    const char * str,
    boost::system::error_code & ec);
  » more...

static address from_string(
    const std::string & str);
  » more...

static address from_string(
    const std::string & str,
    boost::system::error_code & ec);
  » more...

Create an address from an IPv4 address string in dotted decimal form, or from an IPv6 address in hexadecimal notation.

static address from_string(
    const char * str);

Create an address from an IPv4 address string in dotted decimal form, or from an IPv6 address in hexadecimal notation.

static address from_string(
    const char * str,
    boost::system::error_code & ec);

Create an address from an IPv4 address string in dotted decimal form, or from an IPv6 address in hexadecimal notation.

static address from_string(
    const std::string & str);

Create an address from an IPv4 address string in dotted decimal form, or from an IPv6 address in hexadecimal notation.

static address from_string(
    const std::string & str,
    boost::system::error_code & ec);

Determine whether the address is a loopback address.

bool is_loopback() const;

Determine whether the address is a multicast address.

bool is_multicast() const;

Determine whether the address is unspecified.

bool is_unspecified() const;

Get whether the address is an IP version 4 address.

bool is_v4() const;

Get whether the address is an IP version 6 address.

bool is_v6() const;

Compare two addresses for inequality.

friend bool operator!=(
    const address & a1,
    const address & a2);
Requirements

Header: boost/asio/ip/address.hpp

Convenience header: boost/asio.hpp

Compare addresses for ordering.

friend bool operator<(
    const address & a1,
    const address & a2);
Requirements

Header: boost/asio/ip/address.hpp

Convenience header: boost/asio.hpp

Output an address as a string.

template<
    typename Elem,
    typename Traits>
std::basic_ostream< Elem, Traits > & operator<<(
    std::basic_ostream< Elem, Traits > & os,
    const address & addr);

Used to output a human-readable string for a specified address.

Parameters

os

The output stream to which the string will be written.

addr

The address to be written.

Return Value

The output stream.

Compare addresses for ordering.

friend bool operator<=(
    const address & a1,
    const address & a2);
Requirements

Header: boost/asio/ip/address.hpp

Convenience header: boost/asio.hpp

Assign from another address.

address & operator=(
    const address & other);
  » more...

Assign from an IPv4 address.

address & operator=(
    const boost::asio::ip::address_v4 & ipv4_address);
  » more...

Assign from an IPv6 address.

address & operator=(
    const boost::asio::ip::address_v6 & ipv6_address);
  » more...

Assign from another address.

address & operator=(
    const address & other);

Assign from an IPv4 address.

address & operator=(
    const boost::asio::ip::address_v4 & ipv4_address);

Assign from an IPv6 address.

address & operator=(
    const boost::asio::ip::address_v6 & ipv6_address);

Compare two addresses for equality.

friend bool operator==(
    const address & a1,
    const address & a2);
Requirements

Header: boost/asio/ip/address.hpp

Convenience header: boost/asio.hpp

Compare addresses for ordering.

friend bool operator>(
    const address & a1,
    const address & a2);
Requirements

Header: boost/asio/ip/address.hpp

Convenience header: boost/asio.hpp

Compare addresses for ordering.

friend bool operator>=(
    const address & a1,
    const address & a2);
Requirements

Header: boost/asio/ip/address.hpp

Convenience header: boost/asio.hpp

Get the address as a string in dotted decimal format.

std::string to_string() const;
  » more...

std::string to_string(
    boost::system::error_code & ec) const;
  » more...

Get the address as a string in dotted decimal format.

std::string to_string() const;

Get the address as a string in dotted decimal format.

std::string to_string(
    boost::system::error_code & ec) const;

Get the address as an IP version 4 address.

boost::asio::ip::address_v4 to_v4() const;

Get the address as an IP version 6 address.

boost::asio::ip::address_v6 to_v6() const;

Implements IP version 4 style addresses.

class address_v4
Types

Name

Description

bytes_type

The type used to represent an address as an array of bytes.

Member Functions

Name

Description

address_v4

Default constructor.

Construct an address from raw bytes.

Construct an address from a unsigned long in host byte order.

Copy constructor.

any

Obtain an address object that represents any address.

broadcast

Obtain an address object that represents the broadcast address.

Obtain an address object that represents the broadcast address that corresponds to the specified address and netmask.

from_string

Create an address from an IP address string in dotted decimal form.

is_class_a

Determine whether the address is a class A address.

is_class_b

Determine whether the address is a class B address.

is_class_c

Determine whether the address is a class C address.

is_loopback

Determine whether the address is a loopback address.

is_multicast

Determine whether the address is a multicast address.

is_unspecified

Determine whether the address is unspecified.

loopback

Obtain an address object that represents the loopback address.

netmask

Obtain the netmask that corresponds to the address, based on its address class.

operator=

Assign from another address.

to_bytes

Get the address in bytes, in network byte order.

to_string

Get the address as a string in dotted decimal format.

to_ulong

Get the address as an unsigned long in host byte order.

Friends

Name

Description

operator!=

Compare two addresses for inequality.

operator<

Compare addresses for ordering.

operator<=

Compare addresses for ordering.

operator==

Compare two addresses for equality.

operator>

Compare addresses for ordering.

operator>=

Compare addresses for ordering.

Related Functions

Name

Description

operator<<

Output an address as a string.

The ip::address_v4 class provides the ability to use and manipulate IP version 4 addresses.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/ip/address_v4.hpp

Convenience header: boost/asio.hpp

Default constructor.

address_v4();
  » more...

Construct an address from raw bytes.

explicit address_v4(
    const bytes_type & bytes);
  » more...

Construct an address from a unsigned long in host byte order.

explicit address_v4(
    unsigned long addr);
  » more...

Copy constructor.

address_v4(
    const address_v4 & other);
  » more...

Default constructor.

address_v4();

Construct an address from raw bytes.

address_v4(
    const bytes_type & bytes);

Construct an address from a unsigned long in host byte order.

address_v4(
    unsigned long addr);

Copy constructor.

address_v4(
    const address_v4 & other);

Obtain an address object that represents any address.

static address_v4 any();

Obtain an address object that represents the broadcast address.

static address_v4 broadcast();
  » more...

Obtain an address object that represents the broadcast address that corresponds to the specified address and netmask.

static address_v4 broadcast(
    const address_v4 & addr,
    const address_v4 & mask);
  » more...

Obtain an address object that represents the broadcast address.

static address_v4 broadcast();

Obtain an address object that represents the broadcast address that corresponds to the specified address and netmask.

static address_v4 broadcast(
    const address_v4 & addr,
    const address_v4 & mask);

The type used to represent an address as an array of bytes.

typedef array< unsigned char, 4 > bytes_type;
Remarks

This type is defined in terms of the C++0x template std::array when it is available. Otherwise, it uses boost:array.

Requirements

Header: boost/asio/ip/address_v4.hpp

Convenience header: boost/asio.hpp

Create an address from an IP address string in dotted decimal form.

static address_v4 from_string(
    const char * str);
  » more...

static address_v4 from_string(
    const char * str,
    boost::system::error_code & ec);
  » more...

static address_v4 from_string(
    const std::string & str);
  » more...

static address_v4 from_string(
    const std::string & str,
    boost::system::error_code & ec);
  » more...

Create an address from an IP address string in dotted decimal form.

static address_v4 from_string(
    const char * str);

Create an address from an IP address string in dotted decimal form.

static address_v4 from_string(
    const char * str,
    boost::system::error_code & ec);

Create an address from an IP address string in dotted decimal form.

static address_v4 from_string(
    const std::string & str);

Create an address from an IP address string in dotted decimal form.

static address_v4 from_string(
    const std::string & str,
    boost::system::error_code & ec);

Determine whether the address is a class A address.

bool is_class_a() const;

Determine whether the address is a class B address.

bool is_class_b() const;

Determine whether the address is a class C address.

bool is_class_c() const;

Determine whether the address is a loopback address.

bool is_loopback() const;

Determine whether the address is a multicast address.

bool is_multicast() const;

Determine whether the address is unspecified.

bool is_unspecified() const;

Obtain an address object that represents the loopback address.

static address_v4 loopback();

Obtain the netmask that corresponds to the address, based on its address class.

static address_v4 netmask(
    const address_v4 & addr);

Compare two addresses for inequality.

friend bool operator!=(
    const address_v4 & a1,
    const address_v4 & a2);
Requirements

Header: boost/asio/ip/address_v4.hpp

Convenience header: boost/asio.hpp

Compare addresses for ordering.

friend bool operator<(
    const address_v4 & a1,
    const address_v4 & a2);
Requirements

Header: boost/asio/ip/address_v4.hpp

Convenience header: boost/asio.hpp

Output an address as a string.

template<
    typename Elem,
    typename Traits>
std::basic_ostream< Elem, Traits > & operator<<(
    std::basic_ostream< Elem, Traits > & os,
    const address_v4 & addr);

Used to output a human-readable string for a specified address.

Parameters

os

The output stream to which the string will be written.

addr

The address to be written.

Return Value

The output stream.

Compare addresses for ordering.

friend bool operator<=(
    const address_v4 & a1,
    const address_v4 & a2);
Requirements

Header: boost/asio/ip/address_v4.hpp

Convenience header: boost/asio.hpp

Assign from another address.

address_v4 & operator=(
    const address_v4 & other);

Compare two addresses for equality.

friend bool operator==(
    const address_v4 & a1,
    const address_v4 & a2);
Requirements

Header: boost/asio/ip/address_v4.hpp

Convenience header: boost/asio.hpp

Compare addresses for ordering.

friend bool operator>(
    const address_v4 & a1,
    const address_v4 & a2);
Requirements

Header: boost/asio/ip/address_v4.hpp

Convenience header: boost/asio.hpp

Compare addresses for ordering.

friend bool operator>=(
    const address_v4 & a1,
    const address_v4 & a2);
Requirements

Header: boost/asio/ip/address_v4.hpp

Convenience header: boost/asio.hpp

Get the address in bytes, in network byte order.

bytes_type to_bytes() const;

Get the address as a string in dotted decimal format.

std::string to_string() const;
  » more...

std::string to_string(
    boost::system::error_code & ec) const;
  » more...

Get the address as a string in dotted decimal format.

std::string to_string() const;

Get the address as a string in dotted decimal format.

std::string to_string(
    boost::system::error_code & ec) const;

Get the address as an unsigned long in host byte order.

unsigned long to_ulong() const;

Implements IP version 6 style addresses.

class address_v6
Types

Name

Description

bytes_type

The type used to represent an address as an array of bytes.

Member Functions

Name

Description

address_v6

Default constructor.

Construct an address from raw bytes and scope ID.

Copy constructor.

any

Obtain an address object that represents any address.

from_string

Create an address from an IP address string.

is_link_local

Determine whether the address is link local.

is_loopback

Determine whether the address is a loopback address.

is_multicast

Determine whether the address is a multicast address.

is_multicast_global

Determine whether the address is a global multicast address.

is_multicast_link_local

Determine whether the address is a link-local multicast address.

is_multicast_node_local

Determine whether the address is a node-local multicast address.

is_multicast_org_local

Determine whether the address is a org-local multicast address.

is_multicast_site_local

Determine whether the address is a site-local multicast address.

is_site_local

Determine whether the address is site local.

is_unspecified

Determine whether the address is unspecified.

is_v4_compatible

Determine whether the address is an IPv4-compatible address.

is_v4_mapped

Determine whether the address is a mapped IPv4 address.

loopback

Obtain an address object that represents the loopback address.

operator=

Assign from another address.

scope_id

The scope ID of the address.

to_bytes

Get the address in bytes, in network byte order.

to_string

Get the address as a string.

to_v4

Converts an IPv4-mapped or IPv4-compatible address to an IPv4 address.

v4_compatible

Create an IPv4-compatible IPv6 address.

v4_mapped

Create an IPv4-mapped IPv6 address.

Friends

Name

Description

operator!=

Compare two addresses for inequality.

operator<

Compare addresses for ordering.

operator<=

Compare addresses for ordering.

operator==

Compare two addresses for equality.

operator>

Compare addresses for ordering.

operator>=

Compare addresses for ordering.

Related Functions

Name

Description

operator<<

Output an address as a string.

The ip::address_v6 class provides the ability to use and manipulate IP version 6 addresses.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/ip/address_v6.hpp

Convenience header: boost/asio.hpp

Default constructor.

address_v6();
  » more...

Construct an address from raw bytes and scope ID.

explicit address_v6(
    const bytes_type & bytes,
    unsigned long scope_id = 0);
  » more...

Copy constructor.

address_v6(
    const address_v6 & other);
  » more...

Default constructor.

address_v6();

Construct an address from raw bytes and scope ID.

address_v6(
    const bytes_type & bytes,
    unsigned long scope_id = 0);

Copy constructor.

address_v6(
    const address_v6 & other);

Obtain an address object that represents any address.

static address_v6 any();

The type used to represent an address as an array of bytes.

typedef array< unsigned char, 16 > bytes_type;
Remarks

This type is defined in terms of the C++0x template std::array when it is available. Otherwise, it uses boost:array.

Requirements

Header: boost/asio/ip/address_v6.hpp

Convenience header: boost/asio.hpp

Create an address from an IP address string.

static address_v6 from_string(
    const char * str);
  » more...

static address_v6 from_string(
    const char * str,
    boost::system::error_code & ec);
  » more...

static address_v6 from_string(
    const std::string & str);
  » more...

static address_v6 from_string(
    const std::string & str,
    boost::system::error_code & ec);
  » more...

Create an address from an IP address string.

static address_v6 from_string(
    const char * str);

Create an address from an IP address string.

static address_v6 from_string(
    const char * str,
    boost::system::error_code & ec);

Create an address from an IP address string.

static address_v6 from_string(
    const std::string & str);

Create an address from an IP address string.

static address_v6 from_string(
    const std::string & str,
    boost::system::error_code & ec);

Determine whether the address is link local.

bool is_link_local() const;

Determine whether the address is a loopback address.

bool is_loopback() const;

Determine whether the address is a multicast address.

bool is_multicast() const;

Determine whether the address is a global multicast address.

bool is_multicast_global() const;

Determine whether the address is a link-local multicast address.

bool is_multicast_link_local() const;

Determine whether the address is a node-local multicast address.

bool is_multicast_node_local() const;

Determine whether the address is a org-local multicast address.

bool is_multicast_org_local() const;

Determine whether the address is a site-local multicast address.

bool is_multicast_site_local() const;

Determine whether the address is site local.

bool is_site_local() const;

Determine whether the address is unspecified.

bool is_unspecified() const;

Determine whether the address is an IPv4-compatible address.

bool is_v4_compatible() const;

Determine whether the address is a mapped IPv4 address.

bool is_v4_mapped() const;

Obtain an address object that represents the loopback address.

static address_v6 loopback();

Compare two addresses for inequality.

friend bool operator!=(
    const address_v6 & a1,
    const address_v6 & a2);
Requirements

Header: boost/asio/ip/address_v6.hpp

Convenience header: boost/asio.hpp

Compare addresses for ordering.

friend bool operator<(
    const address_v6 & a1,
    const address_v6 & a2);
Requirements

Header: boost/asio/ip/address_v6.hpp

Convenience header: boost/asio.hpp

Output an address as a string.

template<
    typename Elem,
    typename Traits>
std::basic_ostream< Elem, Traits > & operator<<(
    std::basic_ostream< Elem, Traits > & os,
    const address_v6 & addr);

Used to output a human-readable string for a specified address.

Parameters

os

The output stream to which the string will be written.

addr

The address to be written.

Return Value

The output stream.

Compare addresses for ordering.

friend bool operator<=(
    const address_v6 & a1,
    const address_v6 & a2);
Requirements

Header: boost/asio/ip/address_v6.hpp

Convenience header: boost/asio.hpp

Assign from another address.

address_v6 & operator=(
    const address_v6 & other);

Compare two addresses for equality.

friend bool operator==(
    const address_v6 & a1,
    const address_v6 & a2);
Requirements

Header: boost/asio/ip/address_v6.hpp

Convenience header: boost/asio.hpp

Compare addresses for ordering.

friend bool operator>(
    const address_v6 & a1,
    const address_v6 & a2);
Requirements

Header: boost/asio/ip/address_v6.hpp

Convenience header: boost/asio.hpp

Compare addresses for ordering.

friend bool operator>=(
    const address_v6 & a1,
    const address_v6 & a2);
Requirements

Header: boost/asio/ip/address_v6.hpp

Convenience header: boost/asio.hpp

The scope ID of the address.

unsigned long scope_id() const;
  » more...

void scope_id(
    unsigned long id);
  » more...

The scope ID of the address.

unsigned long scope_id() const;

Returns the scope ID associated with the IPv6 address.

The scope ID of the address.

void scope_id(
    unsigned long id);

Modifies the scope ID associated with the IPv6 address.

Get the address in bytes, in network byte order.

bytes_type to_bytes() const;

Get the address as a string.

std::string to_string() const;
  » more...

std::string to_string(
    boost::system::error_code & ec) const;
  » more...

Get the address as a string.

std::string to_string() const;

Get the address as a string.

std::string to_string(
    boost::system::error_code & ec) const;

Converts an IPv4-mapped or IPv4-compatible address to an IPv4 address.

address_v4 to_v4() const;

Create an IPv4-compatible IPv6 address.

static address_v6 v4_compatible(
    const address_v4 & addr);

Create an IPv4-mapped IPv6 address.

static address_v6 v4_mapped(
    const address_v4 & addr);

Describes an endpoint for a version-independent IP socket.

template<
    typename InternetProtocol>
class basic_endpoint
Types

Name

Description

data_type

The type of the endpoint structure. This type is dependent on the underlying implementation of the socket layer.

protocol_type

The protocol type associated with the endpoint.

Member Functions

Name

Description

address

Get the IP address associated with the endpoint.

Set the IP address associated with the endpoint.

basic_endpoint

Default constructor.

Construct an endpoint using a port number, specified in the host's byte order. The IP address will be the any address (i.e. INADDR_ANY or in6addr_any). This constructor would typically be used for accepting new connections.

Construct an endpoint using a port number and an IP address. This constructor may be used for accepting connections on a specific interface or for making a connection to a remote endpoint.

Copy constructor.

capacity

Get the capacity of the endpoint in the native type.

data

Get the underlying endpoint in the native type.

operator=

Assign from another endpoint.

port

Get the port associated with the endpoint. The port number is always in the host's byte order.

Set the port associated with the endpoint. The port number is always in the host's byte order.

protocol

The protocol associated with the endpoint.

resize

Set the underlying size of the endpoint in the native type.

size

Get the underlying size of the endpoint in the native type.

Friends

Name

Description

operator!=

Compare two endpoints for inequality.

operator<

Compare endpoints for ordering.

operator<=

Compare endpoints for ordering.

operator==

Compare two endpoints for equality.

operator>

Compare endpoints for ordering.

operator>=

Compare endpoints for ordering.

Related Functions

Name

Description

operator<<

Output an endpoint as a string.

The ip::basic_endpoint class template describes an endpoint that may be associated with a particular socket.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/ip/basic_endpoint.hpp

Convenience header: boost/asio.hpp

Get the IP address associated with the endpoint.

boost::asio::ip::address address() const;
  » more...

Set the IP address associated with the endpoint.

void address(
    const boost::asio::ip::address & addr);
  » more...

Get the IP address associated with the endpoint.

boost::asio::ip::address address() const;

Set the IP address associated with the endpoint.

void address(
    const boost::asio::ip::address & addr);

Default constructor.

basic_endpoint();
  » more...

Construct an endpoint using a port number, specified in the host's byte order. The IP address will be the any address (i.e. INADDR_ANY or in6addr_any). This constructor would typically be used for accepting new connections.

basic_endpoint(
    const InternetProtocol & internet_protocol,
    unsigned short port_num);
  » more...

Construct an endpoint using a port number and an IP address. This constructor may be used for accepting connections on a specific interface or for making a connection to a remote endpoint.

basic_endpoint(
    const boost::asio::ip::address & addr,
    unsigned short port_num);
  » more...

Copy constructor.

basic_endpoint(
    const basic_endpoint & other);
  » more...

Default constructor.

basic_endpoint();

Construct an endpoint using a port number, specified in the host's byte order. The IP address will be the any address (i.e. INADDR_ANY or in6addr_any). This constructor would typically be used for accepting new connections.

basic_endpoint(
    const InternetProtocol & internet_protocol,
    unsigned short port_num);
Examples

To initialise an IPv4 TCP endpoint for port 1234, use:

boost::asio::ip::tcp::endpoint ep(boost::asio::ip::tcp::v4(), 1234);

To specify an IPv6 UDP endpoint for port 9876, use:

boost::asio::ip::udp::endpoint ep(boost::asio::ip::udp::v6(), 9876);

Construct an endpoint using a port number and an IP address. This constructor may be used for accepting connections on a specific interface or for making a connection to a remote endpoint.

basic_endpoint(
    const boost::asio::ip::address & addr,
    unsigned short port_num);

Copy constructor.

basic_endpoint(
    const basic_endpoint & other);

Get the capacity of the endpoint in the native type.

std::size_t capacity() const;

Get the underlying endpoint in the native type.

data_type * data();
  » more...

const data_type * data() const;
  » more...

Get the underlying endpoint in the native type.

data_type * data();

Get the underlying endpoint in the native type.

const data_type * data() const;

The type of the endpoint structure. This type is dependent on the underlying implementation of the socket layer.

typedef implementation_defined data_type;
Requirements

Header: boost/asio/ip/basic_endpoint.hpp

Convenience header: boost/asio.hpp

Compare two endpoints for inequality.

friend bool operator!=(
    const basic_endpoint< InternetProtocol > & e1,
    const basic_endpoint< InternetProtocol > & e2);
Requirements

Header: boost/asio/ip/basic_endpoint.hpp

Convenience header: boost/asio.hpp

Compare endpoints for ordering.

friend bool operator<(
    const basic_endpoint< InternetProtocol > & e1,
    const basic_endpoint< InternetProtocol > & e2);
Requirements

Header: boost/asio/ip/basic_endpoint.hpp

Convenience header: boost/asio.hpp

Output an endpoint as a string.

std::basic_ostream< Elem, Traits > & operator<<(
    std::basic_ostream< Elem, Traits > & os,
    const basic_endpoint< InternetProtocol > & endpoint);

Used to output a human-readable string for a specified endpoint.

Parameters

os

The output stream to which the string will be written.

endpoint

The endpoint to be written.

Return Value

The output stream.

Compare endpoints for ordering.

friend bool operator<=(
    const basic_endpoint< InternetProtocol > & e1,
    const basic_endpoint< InternetProtocol > & e2);
Requirements

Header: boost/asio/ip/basic_endpoint.hpp

Convenience header: boost/asio.hpp

Assign from another endpoint.

basic_endpoint & operator=(
    const basic_endpoint & other);

Compare two endpoints for equality.

friend bool operator==(
    const basic_endpoint< InternetProtocol > & e1,
    const basic_endpoint< InternetProtocol > & e2);
Requirements

Header: boost/asio/ip/basic_endpoint.hpp

Convenience header: boost/asio.hpp

Compare endpoints for ordering.

friend bool operator>(
    const basic_endpoint< InternetProtocol > & e1,
    const basic_endpoint< InternetProtocol > & e2);
Requirements

Header: boost/asio/ip/basic_endpoint.hpp

Convenience header: boost/asio.hpp

Compare endpoints for ordering.

friend bool operator>=(
    const basic_endpoint< InternetProtocol > & e1,
    const basic_endpoint< InternetProtocol > & e2);
Requirements

Header: boost/asio/ip/basic_endpoint.hpp

Convenience header: boost/asio.hpp

Get the port associated with the endpoint. The port number is always in the host's byte order.

unsigned short port() const;
  » more...

Set the port associated with the endpoint. The port number is always in the host's byte order.

void port(
    unsigned short port_num);
  » more...

Get the port associated with the endpoint. The port number is always in the host's byte order.

unsigned short port() const;

Set the port associated with the endpoint. The port number is always in the host's byte order.

void port(
    unsigned short port_num);

The protocol associated with the endpoint.

protocol_type protocol() const;

The protocol type associated with the endpoint.

typedef InternetProtocol protocol_type;
Requirements

Header: boost/asio/ip/basic_endpoint.hpp

Convenience header: boost/asio.hpp

Set the underlying size of the endpoint in the native type.

void resize(
    std::size_t new_size);

Get the underlying size of the endpoint in the native type.

std::size_t size() const;

Provides endpoint resolution functionality.

template<
    typename InternetProtocol,
    typename ResolverService = resolver_service<InternetProtocol>>
class basic_resolver :
  public basic_io_object< ResolverService >
Types

Name

Description

endpoint_type

The endpoint type.

implementation_type

The underlying implementation type of I/O object.

iterator

The iterator type.

protocol_type

The protocol type.

query

The query type.

service_type

The type of the service that will be used to provide I/O operations.

Member Functions

Name

Description

async_resolve

Asynchronously perform forward resolution of a query to a list of entries.

Asynchronously perform reverse resolution of an endpoint to a list of entries.

basic_resolver

Constructor.

cancel

Cancel any asynchronous operations that are waiting on the resolver.

get_io_service

Get the io_service associated with the object.

resolve

Perform forward resolution of a query to a list of entries.

Perform reverse resolution of an endpoint to a list of entries.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The ip::basic_resolver class template provides the ability to resolve a query to a list of endpoints.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/ip/basic_resolver.hpp

Convenience header: boost/asio.hpp

Asynchronously perform forward resolution of a query to a list of entries.

template<
    typename ResolveHandler>
void-or-deduced async_resolve(
    const query & q,
    ResolveHandler handler);
  » more...

Asynchronously perform reverse resolution of an endpoint to a list of entries.

template<
    typename ResolveHandler>
void-or-deduced async_resolve(
    const endpoint_type & e,
    ResolveHandler handler);
  » more...

Asynchronously perform forward resolution of a query to a list of entries.

template<
    typename ResolveHandler>
void-or-deduced async_resolve(
    const query & q,
    ResolveHandler handler);

This function is used to asynchronously resolve a query into a list of endpoint entries.

Parameters

q

A query object that determines what endpoints will be returned.

handler

The handler to be called when the resolve operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  resolver::iterator iterator             // Forward-only iterator that can
                                          // be used to traverse the list
                                          // of endpoint entries.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

A default constructed iterator represents the end of the list.

A successful resolve operation is guaranteed to pass at least one entry to the handler.

Asynchronously perform reverse resolution of an endpoint to a list of entries.

template<
    typename ResolveHandler>
void-or-deduced async_resolve(
    const endpoint_type & e,
    ResolveHandler handler);

This function is used to asynchronously resolve an endpoint into a list of endpoint entries.

Parameters

e

An endpoint object that determines what endpoints will be returned.

handler

The handler to be called when the resolve operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  resolver::iterator iterator             // Forward-only iterator that can
                                          // be used to traverse the list
                                          // of endpoint entries.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

A default constructed iterator represents the end of the list.

A successful resolve operation is guaranteed to pass at least one entry to the handler.

Constructor.

basic_resolver(
    boost::asio::io_service & io_service);

This constructor creates a ip::basic_resolver.

Parameters

io_service

The io_service object that the resolver will use to dispatch handlers for any asynchronous operations performed on the timer.

Cancel any asynchronous operations that are waiting on the resolver.

void cancel();

This function forces the completion of any pending asynchronous operations on the host resolver. The handler for each cancelled operation will be invoked with the boost::asio::error::operation_aborted error code.

The endpoint type.

typedef InternetProtocol::endpoint endpoint_type;
Requirements

Header: boost/asio/ip/basic_resolver.hpp

Convenience header: boost/asio.hpp

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();
  » more...

const implementation_type & get_implementation() const;
  » more...

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

const implementation_type & get_implementation() const;

Inherited from basic_io_object.

Get the io_service associated with the object.

boost::asio::io_service & get_io_service();

This function may be used to obtain the io_service object that the I/O object uses to dispatch handlers for asynchronous operations.

Return Value

A reference to the io_service object that the I/O object will use to dispatch handlers. Ownership is not transferred to the caller.

Get the service associated with the I/O object.

service_type & get_service();
  » more...

const service_type & get_service() const;
  » more...

Inherited from basic_io_object.

Get the service associated with the I/O object.

service_type & get_service();

Inherited from basic_io_object.

Get the service associated with the I/O object.

const service_type & get_service() const;

Inherited from basic_io_object.

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

implementation_type implementation;

Inherited from basic_io_object.

The underlying implementation type of I/O object.

typedef service_type::implementation_type implementation_type;
Requirements

Header: boost/asio/ip/basic_resolver.hpp

Convenience header: boost/asio.hpp

The iterator type.

typedef basic_resolver_iterator< InternetProtocol > iterator;
Types

Name

Description

difference_type

The type used for the distance between two iterators.

iterator_category

The iterator category.

pointer

The type of the result of applying operator->() to the iterator.

reference

The type of the result of applying operator*() to the iterator.

value_type

The type of the value pointed to by the iterator.

Member Functions

Name

Description

basic_resolver_iterator

Default constructor creates an end iterator.

create

Create an iterator from an addrinfo list returned by getaddrinfo.

Create an iterator from an endpoint, host name and service name.

Create an iterator from a sequence of endpoints, host and service name.

operator *

Dereference an iterator.

operator++

Increment operator (prefix).

Increment operator (postfix).

operator->

Dereference an iterator.

Friends

Name

Description

operator!=

Test two iterators for inequality.

operator==

Test two iterators for equality.

The ip::basic_resolver_iterator class template is used to define iterators over the results returned by a resolver.

The iterator's value_type, obtained when the iterator is dereferenced, is:

const basic_resolver_entry<InternetProtocol>
Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/ip/basic_resolver.hpp

Convenience header: boost/asio.hpp

The protocol type.

typedef InternetProtocol protocol_type;
Requirements

Header: boost/asio/ip/basic_resolver.hpp

Convenience header: boost/asio.hpp

The query type.

typedef basic_resolver_query< InternetProtocol > query;
Types

Name

Description

flags

A bitmask type (C++ Std [lib.bitmask.types]).

protocol_type

The protocol type associated with the endpoint query.

Member Functions

Name

Description

basic_resolver_query

Construct with specified service name for any protocol.

Construct with specified service name for a given protocol.

Construct with specified host name and service name for any protocol.

Construct with specified host name and service name for a given protocol.

hints

Get the hints associated with the query.

host_name

Get the host name associated with the query.

service_name

Get the service name associated with the query.

Data Members

Name

Description

address_configured

Only return IPv4 addresses if a non-loopback IPv4 address is configured for the system. Only return IPv6 addresses if a non-loopback IPv6 address is configured for the system.

all_matching

If used with v4_mapped, return all matching IPv6 and IPv4 addresses.

canonical_name

Determine the canonical name of the host specified in the query.

numeric_host

Host name should be treated as a numeric string defining an IPv4 or IPv6 address and no name resolution should be attempted.

numeric_service

Service name should be treated as a numeric string defining a port number and no name resolution should be attempted.

passive

Indicate that returned endpoint is intended for use as a locally bound socket endpoint.

v4_mapped

If the query protocol family is specified as IPv6, return IPv4-mapped IPv6 addresses on finding no IPv6 addresses.

The ip::basic_resolver_query class template describes a query that can be passed to a resolver.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/ip/basic_resolver.hpp

Convenience header: boost/asio.hpp

Perform forward resolution of a query to a list of entries.

iterator resolve(
    const query & q);
  » more...

iterator resolve(
    const query & q,
    boost::system::error_code & ec);
  » more...

Perform reverse resolution of an endpoint to a list of entries.

iterator resolve(
    const endpoint_type & e);
  » more...

iterator resolve(
    const endpoint_type & e,
    boost::system::error_code & ec);
  » more...

Perform forward resolution of a query to a list of entries.

iterator resolve(
    const query & q);

This function is used to resolve a query into a list of endpoint entries.

Parameters

q

A query object that determines what endpoints will be returned.

Return Value

A forward-only iterator that can be used to traverse the list of endpoint entries.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

A default constructed iterator represents the end of the list.

A successful call to this function is guaranteed to return at least one entry.

Perform forward resolution of a query to a list of entries.

iterator resolve(
    const query & q,
    boost::system::error_code & ec);

This function is used to resolve a query into a list of endpoint entries.

Parameters

q

A query object that determines what endpoints will be returned.

ec

Set to indicate what error occurred, if any.

Return Value

A forward-only iterator that can be used to traverse the list of endpoint entries. Returns a default constructed iterator if an error occurs.

Remarks

A default constructed iterator represents the end of the list.

A successful call to this function is guaranteed to return at least one entry.

Perform reverse resolution of an endpoint to a list of entries.

iterator resolve(
    const endpoint_type & e);

This function is used to resolve an endpoint into a list of endpoint entries.

Parameters

e

An endpoint object that determines what endpoints will be returned.

Return Value

A forward-only iterator that can be used to traverse the list of endpoint entries.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

A default constructed iterator represents the end of the list.

A successful call to this function is guaranteed to return at least one entry.

Perform reverse resolution of an endpoint to a list of entries.

iterator resolve(
    const endpoint_type & e,
    boost::system::error_code & ec);

This function is used to resolve an endpoint into a list of endpoint entries.

Parameters

e

An endpoint object that determines what endpoints will be returned.

ec

Set to indicate what error occurred, if any.

Return Value

A forward-only iterator that can be used to traverse the list of endpoint entries. Returns a default constructed iterator if an error occurs.

Remarks

A default constructed iterator represents the end of the list.

A successful call to this function is guaranteed to return at least one entry.

Inherited from basic_io_object.

(Deprecated: Use get_service().) The service associated with the I/O object.

service_type & service;
Remarks

Available only for services that do not support movability.

Inherited from basic_io_object.

The type of the service that will be used to provide I/O operations.

typedef ResolverService service_type;
Requirements

Header: boost/asio/ip/basic_resolver.hpp

Convenience header: boost/asio.hpp

An entry produced by a resolver.

template<
    typename InternetProtocol>
class basic_resolver_entry
Types

Name

Description

endpoint_type

The endpoint type associated with the endpoint entry.

protocol_type

The protocol type associated with the endpoint entry.

Member Functions

Name

Description

basic_resolver_entry

Default constructor.

Construct with specified endpoint, host name and service name.

endpoint

Get the endpoint associated with the entry.

host_name

Get the host name associated with the entry.

operator endpoint_type

Convert to the endpoint associated with the entry.

service_name

Get the service name associated with the entry.

The ip::basic_resolver_entry class template describes an entry as returned by a resolver.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/ip/basic_resolver_entry.hpp

Convenience header: boost/asio.hpp

Default constructor.

basic_resolver_entry();
  » more...

Construct with specified endpoint, host name and service name.

basic_resolver_entry(
    const endpoint_type & ep,
    const std::string & host,
    const std::string & service);
  » more...

Default constructor.

basic_resolver_entry();

Construct with specified endpoint, host name and service name.

basic_resolver_entry(
    const endpoint_type & ep,
    const std::string & host,
    const std::string & service);

Get the endpoint associated with the entry.

endpoint_type endpoint() const;

The endpoint type associated with the endpoint entry.

typedef InternetProtocol::endpoint endpoint_type;
Requirements

Header: boost/asio/ip/basic_resolver_entry.hpp

Convenience header: boost/asio.hpp

Get the host name associated with the entry.

std::string host_name() const;

Convert to the endpoint associated with the entry.

operator endpoint_type() const;

The protocol type associated with the endpoint entry.

typedef InternetProtocol protocol_type;
Requirements

Header: boost/asio/ip/basic_resolver_entry.hpp

Convenience header: boost/asio.hpp

Get the service name associated with the entry.

std::string service_name() const;

An iterator over the entries produced by a resolver.

template<
    typename InternetProtocol>
class basic_resolver_iterator
Types

Name

Description

difference_type

The type used for the distance between two iterators.

iterator_category

The iterator category.

pointer

The type of the result of applying operator->() to the iterator.

reference

The type of the result of applying operator*() to the iterator.

value_type

The type of the value pointed to by the iterator.

Member Functions

Name

Description

basic_resolver_iterator

Default constructor creates an end iterator.

create

Create an iterator from an addrinfo list returned by getaddrinfo.

Create an iterator from an endpoint, host name and service name.

Create an iterator from a sequence of endpoints, host and service name.

operator *

Dereference an iterator.

operator++

Increment operator (prefix).

Increment operator (postfix).

operator->

Dereference an iterator.

Friends

Name

Description

operator!=

Test two iterators for inequality.

operator==

Test two iterators for equality.

The ip::basic_resolver_iterator class template is used to define iterators over the results returned by a resolver.

The iterator's value_type, obtained when the iterator is dereferenced, is:

const basic_resolver_entry<InternetProtocol>
Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/ip/basic_resolver_iterator.hpp

Convenience header: boost/asio.hpp

Default constructor creates an end iterator.

basic_resolver_iterator();

Create an iterator from an addrinfo list returned by getaddrinfo.

static basic_resolver_iterator create(
    boost::asio::detail::addrinfo_type * address_info,
    const std::string & host_name,
    const std::string & service_name);
  » more...

Create an iterator from an endpoint, host name and service name.

static basic_resolver_iterator create(
    const typename InternetProtocol::endpoint & endpoint,
    const std::string & host_name,
    const std::string & service_name);
  » more...

Create an iterator from a sequence of endpoints, host and service name.

template<
    typename EndpointIterator>
static basic_resolver_iterator create(
    EndpointIterator begin,
    EndpointIterator end,
    const std::string & host_name,
    const std::string & service_name);
  » more...

Create an iterator from an addrinfo list returned by getaddrinfo.

static basic_resolver_iterator create(
    boost::asio::detail::addrinfo_type * address_info,
    const std::string & host_name,
    const std::string & service_name);

Create an iterator from an endpoint, host name and service name.

static basic_resolver_iterator create(
    const typename InternetProtocol::endpoint & endpoint,
    const std::string & host_name,
    const std::string & service_name);

Create an iterator from a sequence of endpoints, host and service name.

template<
    typename EndpointIterator>
static basic_resolver_iterator create(
    EndpointIterator begin,
    EndpointIterator end,
    const std::string & host_name,
    const std::string & service_name);

The type used for the distance between two iterators.

typedef std::ptrdiff_t difference_type;
Requirements

Header: boost/asio/ip/basic_resolver_iterator.hpp

Convenience header: boost/asio.hpp

The iterator category.

typedef std::forward_iterator_tag iterator_category;
Requirements

Header: boost/asio/ip/basic_resolver_iterator.hpp

Convenience header: boost/asio.hpp

Dereference an iterator.

const basic_resolver_entry< InternetProtocol > & operator *() const;

Test two iterators for inequality.

friend bool operator!=(
    const basic_resolver_iterator & a,
    const basic_resolver_iterator & b);
Requirements

Header: boost/asio/ip/basic_resolver_iterator.hpp

Convenience header: boost/asio.hpp

Increment operator (prefix).

basic_resolver_iterator & operator++();
  » more...

Increment operator (postfix).

basic_resolver_iterator operator++(
    int );
  » more...

Increment operator (prefix).

basic_resolver_iterator & operator++();

Increment operator (postfix).

basic_resolver_iterator operator++(
    int );

Dereference an iterator.

const basic_resolver_entry< InternetProtocol > * operator->() const;

Test two iterators for equality.

friend bool operator==(
    const basic_resolver_iterator & a,
    const basic_resolver_iterator & b);
Requirements

Header: boost/asio/ip/basic_resolver_iterator.hpp

Convenience header: boost/asio.hpp

The type of the result of applying operator->() to the iterator.

typedef const basic_resolver_entry< InternetProtocol > * pointer;
Requirements

Header: boost/asio/ip/basic_resolver_iterator.hpp

Convenience header: boost/asio.hpp

The type of the result of applying operator*() to the iterator.

typedef const basic_resolver_entry< InternetProtocol > & reference;
Types

Name

Description

endpoint_type

The endpoint type associated with the endpoint entry.

protocol_type

The protocol type associated with the endpoint entry.

Member Functions

Name

Description

basic_resolver_entry

Default constructor.

Construct with specified endpoint, host name and service name.

endpoint

Get the endpoint associated with the entry.

host_name

Get the host name associated with the entry.

operator endpoint_type

Convert to the endpoint associated with the entry.

service_name

Get the service name associated with the entry.

The ip::basic_resolver_entry class template describes an entry as returned by a resolver.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/ip/basic_resolver_iterator.hpp

Convenience header: boost/asio.hpp

The type of the value pointed to by the iterator.

typedef basic_resolver_entry< InternetProtocol > value_type;
Types

Name

Description

endpoint_type

The endpoint type associated with the endpoint entry.

protocol_type

The protocol type associated with the endpoint entry.

Member Functions

Name

Description

basic_resolver_entry

Default constructor.

Construct with specified endpoint, host name and service name.

endpoint

Get the endpoint associated with the entry.

host_name

Get the host name associated with the entry.

operator endpoint_type

Convert to the endpoint associated with the entry.

service_name

Get the service name associated with the entry.

The ip::basic_resolver_entry class template describes an entry as returned by a resolver.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/ip/basic_resolver_iterator.hpp

Convenience header: boost/asio.hpp

An query to be passed to a resolver.

template<
    typename InternetProtocol>
class basic_resolver_query :
  public ip::resolver_query_base
Types

Name

Description

flags

A bitmask type (C++ Std [lib.bitmask.types]).

protocol_type

The protocol type associated with the endpoint query.

Member Functions

Name

Description

basic_resolver_query

Construct with specified service name for any protocol.

Construct with specified service name for a given protocol.

Construct with specified host name and service name for any protocol.

Construct with specified host name and service name for a given protocol.

hints

Get the hints associated with the query.

host_name

Get the host name associated with the query.

service_name

Get the service name associated with the query.

Data Members

Name

Description

address_configured

Only return IPv4 addresses if a non-loopback IPv4 address is configured for the system. Only return IPv6 addresses if a non-loopback IPv6 address is configured for the system.

all_matching

If used with v4_mapped, return all matching IPv6 and IPv4 addresses.

canonical_name

Determine the canonical name of the host specified in the query.

numeric_host

Host name should be treated as a numeric string defining an IPv4 or IPv6 address and no name resolution should be attempted.

numeric_service

Service name should be treated as a numeric string defining a port number and no name resolution should be attempted.

passive

Indicate that returned endpoint is intended for use as a locally bound socket endpoint.

v4_mapped

If the query protocol family is specified as IPv6, return IPv4-mapped IPv6 addresses on finding no IPv6 addresses.

The ip::basic_resolver_query class template describes a query that can be passed to a resolver.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/ip/basic_resolver_query.hpp

Convenience header: boost/asio.hpp

Inherited from ip::resolver_query_base.

Only return IPv4 addresses if a non-loopback IPv4 address is configured for the system. Only return IPv6 addresses if a non-loopback IPv6 address is configured for the system.

static const flags address_configured = implementation_defined;

Inherited from ip::resolver_query_base.

If used with v4_mapped, return all matching IPv6 and IPv4 addresses.

static const flags all_matching = implementation_defined;

Construct with specified service name for any protocol.

basic_resolver_query(
    const std::string & service,
    resolver_query_base::flags resolve_flags = passive|address_configured);
  » more...

Construct with specified service name for a given protocol.

basic_resolver_query(
    const protocol_type & protocol,
    const std::string & service,
    resolver_query_base::flags resolve_flags = passive|address_configured);
  » more...

Construct with specified host name and service name for any protocol.

basic_resolver_query(
    const std::string & host,
    const std::string & service,
    resolver_query_base::flags resolve_flags = address_configured);
  » more...

Construct with specified host name and service name for a given protocol.

basic_resolver_query(
    const protocol_type & protocol,
    const std::string & host,
    const std::string & service,
    resolver_query_base::flags resolve_flags = address_configured);
  » more...

Construct with specified service name for any protocol.

basic_resolver_query(
    const std::string & service,
    resolver_query_base::flags resolve_flags = passive|address_configured);

This constructor is typically used to perform name resolution for local service binding.

Parameters

service

A string identifying the requested service. This may be a descriptive name or a numeric string corresponding to a port number.

resolve_flags

A set of flags that determine how name resolution should be performed. The default flags are suitable for local service binding.

Remarks

On POSIX systems, service names are typically defined in the file /etc/services. On Windows, service names may be found in the file c:\windows\system32\drivers\etc\services. Operating systems may use additional locations when resolving service names.

Construct with specified service name for a given protocol.

basic_resolver_query(
    const protocol_type & protocol,
    const std::string & service,
    resolver_query_base::flags resolve_flags = passive|address_configured);

This constructor is typically used to perform name resolution for local service binding with a specific protocol version.

Parameters

protocol

A protocol object, normally representing either the IPv4 or IPv6 version of an internet protocol.

service

A string identifying the requested service. This may be a descriptive name or a numeric string corresponding to a port number.

resolve_flags

A set of flags that determine how name resolution should be performed. The default flags are suitable for local service binding.

Remarks

On POSIX systems, service names are typically defined in the file /etc/services. On Windows, service names may be found in the file c:\windows\system32\drivers\etc\services. Operating systems may use additional locations when resolving service names.

Construct with specified host name and service name for any protocol.

basic_resolver_query(
    const std::string & host,
    const std::string & service,
    resolver_query_base::flags resolve_flags = address_configured);

This constructor is typically used to perform name resolution for communication with remote hosts.

Parameters

host

A string identifying a location. May be a descriptive name or a numeric address string. If an empty string and the passive flag has been specified, the resolved endpoints are suitable for local service binding. If an empty string and passive is not specified, the resolved endpoints will use the loopback address.

service

A string identifying the requested service. This may be a descriptive name or a numeric string corresponding to a port number. May be an empty string, in which case all resolved endpoints will have a port number of 0.

resolve_flags

A set of flags that determine how name resolution should be performed. The default flags are suitable for communication with remote hosts.

Remarks

On POSIX systems, host names may be locally defined in the file /etc/hosts. On Windows, host names may be defined in the file c:\windows\system32\drivers\etc\hosts. Remote host name resolution is performed using DNS. Operating systems may use additional locations when resolving host names (such as NETBIOS names on Windows).

On POSIX systems, service names are typically defined in the file /etc/services. On Windows, service names may be found in the file c:\windows\system32\drivers\etc\services. Operating systems may use additional locations when resolving service names.

Construct with specified host name and service name for a given protocol.

basic_resolver_query(
    const protocol_type & protocol,
    const std::string & host,
    const std::string & service,
    resolver_query_base::flags resolve_flags = address_configured);

This constructor is typically used to perform name resolution for communication with remote hosts.

Parameters

protocol

A protocol object, normally representing either the IPv4 or IPv6 version of an internet protocol.

host

A string identifying a location. May be a descriptive name or a numeric address string. If an empty string and the passive flag has been specified, the resolved endpoints are suitable for local service binding. If an empty string and passive is not specified, the resolved endpoints will use the loopback address.

service

A string identifying the requested service. This may be a descriptive name or a numeric string corresponding to a port number. May be an empty string, in which case all resolved endpoints will have a port number of 0.

resolve_flags

A set of flags that determine how name resolution should be performed. The default flags are suitable for communication with remote hosts.

Remarks

On POSIX systems, host names may be locally defined in the file /etc/hosts. On Windows, host names may be defined in the file c:\windows\system32\drivers\etc\hosts. Remote host name resolution is performed using DNS. Operating systems may use additional locations when resolving host names (such as NETBIOS names on Windows).

On POSIX systems, service names are typically defined in the file /etc/services. On Windows, service names may be found in the file c:\windows\system32\drivers\etc\services. Operating systems may use additional locations when resolving service names.

Inherited from ip::resolver_query_base.

Determine the canonical name of the host specified in the query.

static const flags canonical_name = implementation_defined;

Inherited from ip::resolver_query_base.

A bitmask type (C++ Std [lib.bitmask.types]).

typedef unspecified flags;
Requirements

Header: boost/asio/ip/basic_resolver_query.hpp

Convenience header: boost/asio.hpp

Get the hints associated with the query.

const boost::asio::detail::addrinfo_type & hints() const;

Get the host name associated with the query.

std::string host_name() const;

Inherited from ip::resolver_query_base.

Host name should be treated as a numeric string defining an IPv4 or IPv6 address and no name resolution should be attempted.

static const flags numeric_host = implementation_defined;

Inherited from ip::resolver_query_base.

Service name should be treated as a numeric string defining a port number and no name resolution should be attempted.

static const flags numeric_service = implementation_defined;

Inherited from ip::resolver_query_base.

Indicate that returned endpoint is intended for use as a locally bound socket endpoint.

static const flags passive = implementation_defined;

The protocol type associated with the endpoint query.

typedef InternetProtocol protocol_type;
Requirements

Header: boost/asio/ip/basic_resolver_query.hpp

Convenience header: boost/asio.hpp

Get the service name associated with the query.

std::string service_name() const;

Inherited from ip::resolver_query_base.

If the query protocol family is specified as IPv6, return IPv4-mapped IPv6 addresses on finding no IPv6 addresses.

static const flags v4_mapped = implementation_defined;

Get the current host name.

std::string host_name();
  » more...

std::string host_name(
    boost::system::error_code & ec);
  » more...
Requirements

Header: boost/asio/ip/host_name.hpp

Convenience header: boost/asio.hpp

Get the current host name.

std::string host_name();

Get the current host name.

std::string host_name(
    boost::system::error_code & ec);

Encapsulates the flags needed for ICMP.

class icmp
Types

Name

Description

endpoint

The type of a ICMP endpoint.

resolver

The ICMP resolver type.

socket

The ICMP socket type.

Member Functions

Name

Description

family

Obtain an identifier for the protocol family.

protocol

Obtain an identifier for the protocol.

type

Obtain an identifier for the type of the protocol.

v4

Construct to represent the IPv4 ICMP protocol.

v6

Construct to represent the IPv6 ICMP protocol.

Friends

Name

Description

operator!=

Compare two protocols for inequality.

operator==

Compare two protocols for equality.

The ip::icmp class contains flags necessary for ICMP sockets.

Thread Safety

Distinct objects: Safe.

Shared objects: Safe.

Requirements

Header: boost/asio/ip/icmp.hpp

Convenience header: boost/asio.hpp

The type of a ICMP endpoint.

typedef basic_endpoint< icmp > endpoint;
Types

Name

Description

data_type

The type of the endpoint structure. This type is dependent on the underlying implementation of the socket layer.

protocol_type

The protocol type associated with the endpoint.

Member Functions

Name

Description

address

Get the IP address associated with the endpoint.

Set the IP address associated with the endpoint.

basic_endpoint

Default constructor.

Construct an endpoint using a port number, specified in the host's byte order. The IP address will be the any address (i.e. INADDR_ANY or in6addr_any). This constructor would typically be used for accepting new connections.

Construct an endpoint using a port number and an IP address. This constructor may be used for accepting connections on a specific interface or for making a connection to a remote endpoint.

Copy constructor.

capacity

Get the capacity of the endpoint in the native type.

data

Get the underlying endpoint in the native type.

operator=

Assign from another endpoint.

port

Get the port associated with the endpoint. The port number is always in the host's byte order.

Set the port associated with the endpoint. The port number is always in the host's byte order.

protocol

The protocol associated with the endpoint.

resize

Set the underlying size of the endpoint in the native type.

size

Get the underlying size of the endpoint in the native type.

Friends

Name

Description

operator!=

Compare two endpoints for inequality.

operator<

Compare endpoints for ordering.

operator<=

Compare endpoints for ordering.

operator==

Compare two endpoints for equality.

operator>

Compare endpoints for ordering.

operator>=

Compare endpoints for ordering.

Related Functions

Name

Description

operator<<

Output an endpoint as a string.

The ip::basic_endpoint class template describes an endpoint that may be associated with a particular socket.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/ip/icmp.hpp

Convenience header: boost/asio.hpp

Obtain an identifier for the protocol family.

int family() const;

Compare two protocols for inequality.

friend bool operator!=(
    const icmp & p1,
    const icmp & p2);
Requirements

Header: boost/asio/ip/icmp.hpp

Convenience header: boost/asio.hpp

Compare two protocols for equality.

friend bool operator==(
    const icmp & p1,
    const icmp & p2);
Requirements

Header: boost/asio/ip/icmp.hpp

Convenience header: boost/asio.hpp

Obtain an identifier for the protocol.

int protocol() const;

The ICMP resolver type.

typedef basic_resolver< icmp > resolver;
Types

Name

Description

endpoint_type

The endpoint type.

implementation_type

The underlying implementation type of I/O object.

iterator

The iterator type.

protocol_type

The protocol type.

query

The query type.

service_type

The type of the service that will be used to provide I/O operations.

Member Functions

Name

Description

async_resolve

Asynchronously perform forward resolution of a query to a list of entries.

Asynchronously perform reverse resolution of an endpoint to a list of entries.

basic_resolver

Constructor.

cancel

Cancel any asynchronous operations that are waiting on the resolver.

get_io_service

Get the io_service associated with the object.

resolve

Perform forward resolution of a query to a list of entries.

Perform reverse resolution of an endpoint to a list of entries.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The ip::basic_resolver class template provides the ability to resolve a query to a list of endpoints.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/ip/icmp.hpp

Convenience header: boost/asio.hpp

The ICMP socket type.

typedef basic_raw_socket< icmp > socket;
Types

Name

Description

broadcast

Socket option to permit sending of broadcast messages.

bytes_readable

IO control command to get the amount of data that can be read without blocking.

debug

Socket option to enable socket-level debugging.

do_not_route

Socket option to prevent routing, use local interfaces only.

enable_connection_aborted

Socket option to report aborted connections on accept.

endpoint_type

The endpoint type.

implementation_type

The underlying implementation type of I/O object.

keep_alive

Socket option to send keep-alives.

linger

Socket option to specify whether the socket lingers on close if unsent data is present.

lowest_layer_type

A basic_socket is always the lowest layer.

message_flags

Bitmask type for flags that can be passed to send and receive operations.

native_handle_type

The native representation of a socket.

native_type

(Deprecated: Use native_handle_type.) The native representation of a socket.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

protocol_type

The protocol type.

receive_buffer_size

Socket option for the receive buffer size of a socket.

receive_low_watermark

Socket option for the receive low watermark.

reuse_address

Socket option to allow the socket to be bound to an address that is already in use.

send_buffer_size

Socket option for the send buffer size of a socket.

send_low_watermark

Socket option for the send low watermark.

service_type

The type of the service that will be used to provide I/O operations.

shutdown_type

Different ways a socket may be shutdown.

Member Functions

Name

Description

assign

Assign an existing native socket to the socket.

async_connect

Start an asynchronous connect.

async_receive

Start an asynchronous receive on a connected socket.

async_receive_from

Start an asynchronous receive.

async_send

Start an asynchronous send on a connected socket.

async_send_to

Start an asynchronous send.

at_mark

Determine whether the socket is at the out-of-band data mark.

available

Determine the number of bytes available for reading.

basic_raw_socket

Construct a basic_raw_socket without opening it.

Construct and open a basic_raw_socket.

Construct a basic_raw_socket, opening it and binding it to the given local endpoint.

Construct a basic_raw_socket on an existing native socket.

Move-construct a basic_raw_socket from another.

Move-construct a basic_raw_socket from a socket of another protocol type.

bind

Bind the socket to the given local endpoint.

cancel

Cancel all asynchronous operations associated with the socket.

close

Close the socket.

connect

Connect the socket to the specified endpoint.

get_io_service

Get the io_service associated with the object.

get_option

Get an option from the socket.

io_control

Perform an IO control command on the socket.

is_open

Determine whether the socket is open.

local_endpoint

Get the local endpoint of the socket.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native socket representation.

native_handle

Get the native socket representation.

native_non_blocking

Gets the non-blocking mode of the native socket implementation.

Sets the non-blocking mode of the native socket implementation.

non_blocking

Gets the non-blocking mode of the socket.

Sets the non-blocking mode of the socket.

open

Open the socket using the specified protocol.

operator=

Move-assign a basic_raw_socket from another.

Move-assign a basic_raw_socket from a socket of another protocol type.

receive

Receive some data on a connected socket.

receive_from

Receive raw data with the endpoint of the sender.

remote_endpoint

Get the remote endpoint of the socket.

send

Send some data on a connected socket.

send_to

Send raw data to the specified endpoint.

set_option

Set an option on the socket.

shutdown

Disable sends or receives on the socket.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Data Members

Name

Description

max_connections

The maximum length of the queue of pending incoming connections.

message_do_not_route

Specify that the data should not be subject to routing.

message_end_of_record

Specifies that the data marks the end of a record.

message_out_of_band

Process out-of-band data.

message_peek

Peek at incoming data without removing it from the input queue.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_raw_socket class template provides asynchronous and blocking raw-oriented socket functionality.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/ip/icmp.hpp

Convenience header: boost/asio.hpp

Obtain an identifier for the type of the protocol.

int type() const;

Construct to represent the IPv4 ICMP protocol.

static icmp v4();

Construct to represent the IPv6 ICMP protocol.

static icmp v6();

Socket option determining whether outgoing multicast packets will be received on the same socket if it is a member of the multicast group.

typedef implementation_defined enable_loopback;

Implements the IPPROTO_IP/IP_MULTICAST_LOOP socket option.

Examples

Setting the option:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::ip::multicast::enable_loopback option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::ip::multicast::enable_loopback option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/ip/multicast.hpp

Convenience header: boost/asio.hpp

Socket option for time-to-live associated with outgoing multicast packets.

typedef implementation_defined hops;

Implements the IPPROTO_IP/IP_MULTICAST_TTL socket option.

Examples

Setting the option:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::ip::multicast::hops option(4);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::ip::multicast::hops option;
socket.get_option(option);
int ttl = option.value();
Requirements

Header: boost/asio/ip/multicast.hpp

Convenience header: boost/asio.hpp

Socket option to join a multicast group on a specified interface.

typedef implementation_defined join_group;

Implements the IPPROTO_IP/IP_ADD_MEMBERSHIP socket option.

Examples

Setting the option to join a multicast group:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::ip::address multicast_address =
  boost::asio::ip::address::from_string("225.0.0.1");
boost::asio::ip::multicast::join_group option(multicast_address);
socket.set_option(option);
Requirements

Header: boost/asio/ip/multicast.hpp

Convenience header: boost/asio.hpp

Socket option to leave a multicast group on a specified interface.

typedef implementation_defined leave_group;

Implements the IPPROTO_IP/IP_DROP_MEMBERSHIP socket option.

Examples

Setting the option to leave a multicast group:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::ip::address multicast_address =
  boost::asio::ip::address::from_string("225.0.0.1");
boost::asio::ip::multicast::leave_group option(multicast_address);
socket.set_option(option);
Requirements

Header: boost/asio/ip/multicast.hpp

Convenience header: boost/asio.hpp

Socket option for local interface to use for outgoing multicast packets.

typedef implementation_defined outbound_interface;

Implements the IPPROTO_IP/IP_MULTICAST_IF socket option.

Examples

Setting the option:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::ip::address_v4 local_interface =
  boost::asio::ip::address_v4::from_string("1.2.3.4");
boost::asio::ip::multicast::outbound_interface option(local_interface);
socket.set_option(option);
Requirements

Header: boost/asio/ip/multicast.hpp

Convenience header: boost/asio.hpp

The ip::resolver_query_base class is used as a base for the ip::basic_resolver_query class templates to provide a common place to define the flag constants.

class resolver_query_base
Types

Name

Description

flags

A bitmask type (C++ Std [lib.bitmask.types]).

Protected Member Functions

Name

Description

~resolver_query_base

Protected destructor to prevent deletion through this type.

Data Members

Name

Description

address_configured

Only return IPv4 addresses if a non-loopback IPv4 address is configured for the system. Only return IPv6 addresses if a non-loopback IPv6 address is configured for the system.

all_matching

If used with v4_mapped, return all matching IPv6 and IPv4 addresses.

canonical_name

Determine the canonical name of the host specified in the query.

numeric_host

Host name should be treated as a numeric string defining an IPv4 or IPv6 address and no name resolution should be attempted.

numeric_service

Service name should be treated as a numeric string defining a port number and no name resolution should be attempted.

passive

Indicate that returned endpoint is intended for use as a locally bound socket endpoint.

v4_mapped

If the query protocol family is specified as IPv6, return IPv4-mapped IPv6 addresses on finding no IPv6 addresses.

Requirements

Header: boost/asio/ip/resolver_query_base.hpp

Convenience header: boost/asio.hpp

Only return IPv4 addresses if a non-loopback IPv4 address is configured for the system. Only return IPv6 addresses if a non-loopback IPv6 address is configured for the system.

static const flags address_configured = implementation_defined;

If used with v4_mapped, return all matching IPv6 and IPv4 addresses.

static const flags all_matching = implementation_defined;

Determine the canonical name of the host specified in the query.

static const flags canonical_name = implementation_defined;

A bitmask type (C++ Std [lib.bitmask.types]).

typedef unspecified flags;
Requirements

Header: boost/asio/ip/resolver_query_base.hpp

Convenience header: boost/asio.hpp

Host name should be treated as a numeric string defining an IPv4 or IPv6 address and no name resolution should be attempted.

static const flags numeric_host = implementation_defined;

Service name should be treated as a numeric string defining a port number and no name resolution should be attempted.

static const flags numeric_service = implementation_defined;

Indicate that returned endpoint is intended for use as a locally bound socket endpoint.

static const flags passive = implementation_defined;

If the query protocol family is specified as IPv6, return IPv4-mapped IPv6 addresses on finding no IPv6 addresses.

static const flags v4_mapped = implementation_defined;

Protected destructor to prevent deletion through this type.

~resolver_query_base();

Default service implementation for a resolver.

template<
    typename InternetProtocol>
class resolver_service :
  public io_service::service
Types

Name

Description

endpoint_type

The endpoint type.

implementation_type

The type of a resolver implementation.

iterator_type

The iterator type.

protocol_type

The protocol type.

query_type

The query type.

Member Functions

Name

Description

async_resolve

Asynchronously resolve a query to a list of entries.

Asynchronously resolve an endpoint to a list of entries.

cancel

Cancel pending asynchronous operations.

construct

Construct a new resolver implementation.

destroy

Destroy a resolver implementation.

get_io_service

Get the io_service object that owns the service.

resolve

Resolve a query to a list of entries.

Resolve an endpoint to a list of entries.

resolver_service

Construct a new resolver service for the specified io_service.

Data Members

Name

Description

id

The unique service identifier.

Requirements

Header: boost/asio/ip/resolver_service.hpp

Convenience header: boost/asio.hpp

Asynchronously resolve a query to a list of entries.

template<
    typename ResolveHandler>
void-or-deduced async_resolve(
    implementation_type & impl,
    const query_type & query,
    ResolveHandler handler);
  » more...

Asynchronously resolve an endpoint to a list of entries.

template<
    typename ResolveHandler>
void-or-deduced async_resolve(
    implementation_type & impl,
    const endpoint_type & endpoint,
    ResolveHandler handler);
  » more...

Asynchronously resolve a query to a list of entries.

template<
    typename ResolveHandler>
void-or-deduced async_resolve(
    implementation_type & impl,
    const query_type & query,
    ResolveHandler handler);

Asynchronously resolve an endpoint to a list of entries.

template<
    typename ResolveHandler>
void-or-deduced async_resolve(
    implementation_type & impl,
    const endpoint_type & endpoint,
    ResolveHandler handler);

Cancel pending asynchronous operations.

void cancel(
    implementation_type & impl);

Construct a new resolver implementation.

void construct(
    implementation_type & impl);

Destroy a resolver implementation.

void destroy(
    implementation_type & impl);

The endpoint type.

typedef InternetProtocol::endpoint endpoint_type;
Requirements

Header: boost/asio/ip/resolver_service.hpp

Convenience header: boost/asio.hpp

Inherited from io_service.

Get the io_service object that owns the service.

boost::asio::io_service & get_io_service();

The unique service identifier.

static boost::asio::io_service::id id;

The type of a resolver implementation.

typedef implementation_defined implementation_type;
Requirements

Header: boost/asio/ip/resolver_service.hpp

Convenience header: boost/asio.hpp

The iterator type.

typedef basic_resolver_iterator< InternetProtocol > iterator_type;
Types

Name

Description

difference_type

The type used for the distance between two iterators.

iterator_category

The iterator category.

pointer

The type of the result of applying operator->() to the iterator.

reference

The type of the result of applying operator*() to the iterator.

value_type

The type of the value pointed to by the iterator.

Member Functions

Name

Description

basic_resolver_iterator

Default constructor creates an end iterator.

create

Create an iterator from an addrinfo list returned by getaddrinfo.

Create an iterator from an endpoint, host name and service name.

Create an iterator from a sequence of endpoints, host and service name.

operator *

Dereference an iterator.

operator++

Increment operator (prefix).

Increment operator (postfix).

operator->

Dereference an iterator.

Friends

Name

Description

operator!=

Test two iterators for inequality.

operator==

Test two iterators for equality.

The ip::basic_resolver_iterator class template is used to define iterators over the results returned by a resolver.

The iterator's value_type, obtained when the iterator is dereferenced, is:

const basic_resolver_entry<InternetProtocol>
Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/ip/resolver_service.hpp

Convenience header: boost/asio.hpp

The protocol type.

typedef InternetProtocol protocol_type;
Requirements

Header: boost/asio/ip/resolver_service.hpp

Convenience header: boost/asio.hpp

The query type.

typedef basic_resolver_query< InternetProtocol > query_type;
Types

Name

Description

flags

A bitmask type (C++ Std [lib.bitmask.types]).

protocol_type

The protocol type associated with the endpoint query.

Member Functions

Name

Description

basic_resolver_query

Construct with specified service name for any protocol.

Construct with specified service name for a given protocol.

Construct with specified host name and service name for any protocol.

Construct with specified host name and service name for a given protocol.

hints

Get the hints associated with the query.

host_name

Get the host name associated with the query.

service_name

Get the service name associated with the query.

Data Members

Name

Description

address_configured

Only return IPv4 addresses if a non-loopback IPv4 address is configured for the system. Only return IPv6 addresses if a non-loopback IPv6 address is configured for the system.

all_matching

If used with v4_mapped, return all matching IPv6 and IPv4 addresses.

canonical_name

Determine the canonical name of the host specified in the query.

numeric_host

Host name should be treated as a numeric string defining an IPv4 or IPv6 address and no name resolution should be attempted.

numeric_service

Service name should be treated as a numeric string defining a port number and no name resolution should be attempted.

passive

Indicate that returned endpoint is intended for use as a locally bound socket endpoint.

v4_mapped

If the query protocol family is specified as IPv6, return IPv4-mapped IPv6 addresses on finding no IPv6 addresses.

The ip::basic_resolver_query class template describes a query that can be passed to a resolver.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/ip/resolver_service.hpp

Convenience header: boost/asio.hpp

Resolve a query to a list of entries.

iterator_type resolve(
    implementation_type & impl,
    const query_type & query,
    boost::system::error_code & ec);
  » more...

Resolve an endpoint to a list of entries.

iterator_type resolve(
    implementation_type & impl,
    const endpoint_type & endpoint,
    boost::system::error_code & ec);
  » more...

Resolve a query to a list of entries.

iterator_type resolve(
    implementation_type & impl,
    const query_type & query,
    boost::system::error_code & ec);

Resolve an endpoint to a list of entries.

iterator_type resolve(
    implementation_type & impl,
    const endpoint_type & endpoint,
    boost::system::error_code & ec);

Construct a new resolver service for the specified io_service.

resolver_service(
    boost::asio::io_service & io_service);

Encapsulates the flags needed for TCP.

class tcp
Types

Name

Description

acceptor

The TCP acceptor type.

endpoint

The type of a TCP endpoint.

iostream

The TCP iostream type.

no_delay

Socket option for disabling the Nagle algorithm.

resolver

The TCP resolver type.

socket

The TCP socket type.

Member Functions

Name

Description

family

Obtain an identifier for the protocol family.

protocol

Obtain an identifier for the protocol.

type

Obtain an identifier for the type of the protocol.

v4

Construct to represent the IPv4 TCP protocol.

v6

Construct to represent the IPv6 TCP protocol.

Friends

Name

Description

operator!=

Compare two protocols for inequality.

operator==

Compare two protocols for equality.

The ip::tcp class contains flags necessary for TCP sockets.

Thread Safety

Distinct objects: Safe.

Shared objects: Safe.

Requirements

Header: boost/asio/ip/tcp.hpp

Convenience header: boost/asio.hpp

The TCP acceptor type.

typedef basic_socket_acceptor< tcp > acceptor;
Types

Name

Description

broadcast

Socket option to permit sending of broadcast messages.

bytes_readable

IO control command to get the amount of data that can be read without blocking.

debug

Socket option to enable socket-level debugging.

do_not_route

Socket option to prevent routing, use local interfaces only.

enable_connection_aborted

Socket option to report aborted connections on accept.

endpoint_type

The endpoint type.

implementation_type

The underlying implementation type of I/O object.

keep_alive

Socket option to send keep-alives.

linger

Socket option to specify whether the socket lingers on close if unsent data is present.

message_flags

Bitmask type for flags that can be passed to send and receive operations.

native_handle_type

The native representation of an acceptor.

native_type

(Deprecated: Use native_handle_type.) The native representation of an acceptor.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

protocol_type

The protocol type.

receive_buffer_size

Socket option for the receive buffer size of a socket.

receive_low_watermark

Socket option for the receive low watermark.

reuse_address

Socket option to allow the socket to be bound to an address that is already in use.

send_buffer_size

Socket option for the send buffer size of a socket.

send_low_watermark

Socket option for the send low watermark.

service_type

The type of the service that will be used to provide I/O operations.

shutdown_type

Different ways a socket may be shutdown.

Member Functions

Name

Description

accept

Accept a new connection.

Accept a new connection and obtain the endpoint of the peer.

assign

Assigns an existing native acceptor to the acceptor.

async_accept

Start an asynchronous accept.

basic_socket_acceptor

Construct an acceptor without opening it.

Construct an open acceptor.

Construct an acceptor opened on the given endpoint.

Construct a basic_socket_acceptor on an existing native acceptor.

Move-construct a basic_socket_acceptor from another.

Move-construct a basic_socket_acceptor from an acceptor of another protocol type.

bind

Bind the acceptor to the given local endpoint.

cancel

Cancel all asynchronous operations associated with the acceptor.

close

Close the acceptor.

get_io_service

Get the io_service associated with the object.

get_option

Get an option from the acceptor.

io_control

Perform an IO control command on the acceptor.

is_open

Determine whether the acceptor is open.

listen

Place the acceptor into the state where it will listen for new connections.

local_endpoint

Get the local endpoint of the acceptor.

native

(Deprecated: Use native_handle().) Get the native acceptor representation.

native_handle

Get the native acceptor representation.

native_non_blocking

Gets the non-blocking mode of the native acceptor implementation.

Sets the non-blocking mode of the native acceptor implementation.

non_blocking

Gets the non-blocking mode of the acceptor.

Sets the non-blocking mode of the acceptor.

open

Open the acceptor using the specified protocol.

operator=

Move-assign a basic_socket_acceptor from another.

Move-assign a basic_socket_acceptor from an acceptor of another protocol type.

set_option

Set an option on the acceptor.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Data Members

Name

Description

max_connections

The maximum length of the queue of pending incoming connections.

message_do_not_route

Specify that the data should not be subject to routing.

message_end_of_record

Specifies that the data marks the end of a record.

message_out_of_band

Process out-of-band data.

message_peek

Peek at incoming data without removing it from the input queue.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_socket_acceptor class template is used for accepting new socket connections.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Example

Opening a socket acceptor with the SO_REUSEADDR option enabled:

boost::asio::ip::tcp::acceptor acceptor(io_service);
boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), port);
acceptor.open(endpoint.protocol());
acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor.bind(endpoint);
acceptor.listen();
Requirements

Header: boost/asio/ip/tcp.hpp

Convenience header: boost/asio.hpp

The type of a TCP endpoint.

typedef basic_endpoint< tcp > endpoint;
Types

Name

Description

data_type

The type of the endpoint structure. This type is dependent on the underlying implementation of the socket layer.

protocol_type

The protocol type associated with the endpoint.

Member Functions

Name

Description

address

Get the IP address associated with the endpoint.

Set the IP address associated with the endpoint.

basic_endpoint

Default constructor.

Construct an endpoint using a port number, specified in the host's byte order. The IP address will be the any address (i.e. INADDR_ANY or in6addr_any). This constructor would typically be used for accepting new connections.

Construct an endpoint using a port number and an IP address. This constructor may be used for accepting connections on a specific interface or for making a connection to a remote endpoint.

Copy constructor.

capacity

Get the capacity of the endpoint in the native type.

data

Get the underlying endpoint in the native type.

operator=

Assign from another endpoint.

port

Get the port associated with the endpoint. The port number is always in the host's byte order.

Set the port associated with the endpoint. The port number is always in the host's byte order.

protocol

The protocol associated with the endpoint.

resize

Set the underlying size of the endpoint in the native type.

size

Get the underlying size of the endpoint in the native type.

Friends

Name

Description

operator!=

Compare two endpoints for inequality.

operator<

Compare endpoints for ordering.

operator<=

Compare endpoints for ordering.

operator==

Compare two endpoints for equality.

operator>

Compare endpoints for ordering.

operator>=

Compare endpoints for ordering.

Related Functions

Name

Description

operator<<

Output an endpoint as a string.

The ip::basic_endpoint class template describes an endpoint that may be associated with a particular socket.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/ip/tcp.hpp

Convenience header: boost/asio.hpp

Obtain an identifier for the protocol family.

int family() const;

The TCP iostream type.

typedef basic_socket_iostream< tcp > iostream;
Types

Name

Description

duration_type

The duration type.

endpoint_type

The endpoint type.

time_type

The time type.

Member Functions

Name

Description

basic_socket_iostream

Construct a basic_socket_iostream without establishing a connection.

Establish a connection to an endpoint corresponding to a resolver query.

close

Close the connection.

connect

Establish a connection to an endpoint corresponding to a resolver query.

error

Get the last error associated with the stream.

expires_at

Get the stream's expiry time as an absolute time.

Set the stream's expiry time as an absolute time.

expires_from_now

Get the timer's expiry time relative to now.

Set the stream's expiry time relative to now.

rdbuf

Return a pointer to the underlying streambuf.

Requirements

Header: boost/asio/ip/tcp.hpp

Convenience header: boost/asio.hpp

Socket option for disabling the Nagle algorithm.

typedef implementation_defined no_delay;

Implements the IPPROTO_TCP/TCP_NODELAY socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::no_delay option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::tcp::no_delay option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/ip/tcp.hpp

Convenience header: boost/asio.hpp

Compare two protocols for inequality.

friend bool operator!=(
    const tcp & p1,
    const tcp & p2);
Requirements

Header: boost/asio/ip/tcp.hpp

Convenience header: boost/asio.hpp

Compare two protocols for equality.

friend bool operator==(
    const tcp & p1,
    const tcp & p2);
Requirements

Header: boost/asio/ip/tcp.hpp

Convenience header: boost/asio.hpp

Obtain an identifier for the protocol.

int protocol() const;

The TCP resolver type.

typedef basic_resolver< tcp > resolver;
Types

Name

Description

endpoint_type

The endpoint type.

implementation_type

The underlying implementation type of I/O object.

iterator

The iterator type.

protocol_type

The protocol type.

query

The query type.

service_type

The type of the service that will be used to provide I/O operations.

Member Functions

Name

Description

async_resolve

Asynchronously perform forward resolution of a query to a list of entries.

Asynchronously perform reverse resolution of an endpoint to a list of entries.

basic_resolver

Constructor.

cancel

Cancel any asynchronous operations that are waiting on the resolver.

get_io_service

Get the io_service associated with the object.

resolve

Perform forward resolution of a query to a list of entries.

Perform reverse resolution of an endpoint to a list of entries.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The ip::basic_resolver class template provides the ability to resolve a query to a list of endpoints.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/ip/tcp.hpp

Convenience header: boost/asio.hpp

The TCP socket type.

typedef basic_stream_socket< tcp > socket;
Types

Name

Description

broadcast

Socket option to permit sending of broadcast messages.

bytes_readable

IO control command to get the amount of data that can be read without blocking.

debug

Socket option to enable socket-level debugging.

do_not_route

Socket option to prevent routing, use local interfaces only.

enable_connection_aborted

Socket option to report aborted connections on accept.

endpoint_type

The endpoint type.

implementation_type

The underlying implementation type of I/O object.

keep_alive

Socket option to send keep-alives.

linger

Socket option to specify whether the socket lingers on close if unsent data is present.

lowest_layer_type

A basic_socket is always the lowest layer.

message_flags

Bitmask type for flags that can be passed to send and receive operations.

native_handle_type

The native representation of a socket.

native_type

(Deprecated: Use native_handle_type.) The native representation of a socket.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

protocol_type

The protocol type.

receive_buffer_size

Socket option for the receive buffer size of a socket.

receive_low_watermark

Socket option for the receive low watermark.

reuse_address

Socket option to allow the socket to be bound to an address that is already in use.

send_buffer_size

Socket option for the send buffer size of a socket.

send_low_watermark

Socket option for the send low watermark.

service_type

The type of the service that will be used to provide I/O operations.

shutdown_type

Different ways a socket may be shutdown.

Member Functions

Name

Description

assign

Assign an existing native socket to the socket.

async_connect

Start an asynchronous connect.

async_read_some

Start an asynchronous read.

async_receive

Start an asynchronous receive.

async_send

Start an asynchronous send.

async_write_some

Start an asynchronous write.

at_mark

Determine whether the socket is at the out-of-band data mark.

available

Determine the number of bytes available for reading.

basic_stream_socket

Construct a basic_stream_socket without opening it.

Construct and open a basic_stream_socket.

Construct a basic_stream_socket, opening it and binding it to the given local endpoint.

Construct a basic_stream_socket on an existing native socket.

Move-construct a basic_stream_socket from another.

Move-construct a basic_stream_socket from a socket of another protocol type.

bind

Bind the socket to the given local endpoint.

cancel

Cancel all asynchronous operations associated with the socket.

close

Close the socket.

connect

Connect the socket to the specified endpoint.

get_io_service

Get the io_service associated with the object.

get_option

Get an option from the socket.

io_control

Perform an IO control command on the socket.

is_open

Determine whether the socket is open.

local_endpoint

Get the local endpoint of the socket.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native socket representation.

native_handle

Get the native socket representation.

native_non_blocking

Gets the non-blocking mode of the native socket implementation.

Sets the non-blocking mode of the native socket implementation.

non_blocking

Gets the non-blocking mode of the socket.

Sets the non-blocking mode of the socket.

open

Open the socket using the specified protocol.

operator=

Move-assign a basic_stream_socket from another.

Move-assign a basic_stream_socket from a socket of another protocol type.

read_some

Read some data from the socket.

receive

Receive some data on the socket.

Receive some data on a connected socket.

remote_endpoint

Get the remote endpoint of the socket.

send

Send some data on the socket.

set_option

Set an option on the socket.

shutdown

Disable sends or receives on the socket.

write_some

Write some data to the socket.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Data Members

Name

Description

max_connections

The maximum length of the queue of pending incoming connections.

message_do_not_route

Specify that the data should not be subject to routing.

message_end_of_record

Specifies that the data marks the end of a record.

message_out_of_band

Process out-of-band data.

message_peek

Peek at incoming data without removing it from the input queue.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_stream_socket class template provides asynchronous and blocking stream-oriented socket functionality.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/ip/tcp.hpp

Convenience header: boost/asio.hpp

Obtain an identifier for the type of the protocol.

int type() const;

Construct to represent the IPv4 TCP protocol.

static tcp v4();

Construct to represent the IPv6 TCP protocol.

static tcp v6();

Encapsulates the flags needed for UDP.

class udp
Types

Name

Description

endpoint

The type of a UDP endpoint.

resolver

The UDP resolver type.

socket

The UDP socket type.

Member Functions

Name

Description

family

Obtain an identifier for the protocol family.

protocol

Obtain an identifier for the protocol.

type

Obtain an identifier for the type of the protocol.

v4

Construct to represent the IPv4 UDP protocol.

v6

Construct to represent the IPv6 UDP protocol.

Friends

Name

Description

operator!=

Compare two protocols for inequality.

operator==

Compare two protocols for equality.

The ip::udp class contains flags necessary for UDP sockets.

Thread Safety

Distinct objects: Safe.

Shared objects: Safe.

Requirements

Header: boost/asio/ip/udp.hpp

Convenience header: boost/asio.hpp

The type of a UDP endpoint.

typedef basic_endpoint< udp > endpoint;
Types

Name

Description

data_type

The type of the endpoint structure. This type is dependent on the underlying implementation of the socket layer.

protocol_type

The protocol type associated with the endpoint.

Member Functions

Name

Description

address

Get the IP address associated with the endpoint.

Set the IP address associated with the endpoint.

basic_endpoint

Default constructor.

Construct an endpoint using a port number, specified in the host's byte order. The IP address will be the any address (i.e. INADDR_ANY or in6addr_any). This constructor would typically be used for accepting new connections.

Construct an endpoint using a port number and an IP address. This constructor may be used for accepting connections on a specific interface or for making a connection to a remote endpoint.

Copy constructor.

capacity

Get the capacity of the endpoint in the native type.

data

Get the underlying endpoint in the native type.

operator=

Assign from another endpoint.

port

Get the port associated with the endpoint. The port number is always in the host's byte order.

Set the port associated with the endpoint. The port number is always in the host's byte order.

protocol

The protocol associated with the endpoint.

resize

Set the underlying size of the endpoint in the native type.

size

Get the underlying size of the endpoint in the native type.

Friends

Name

Description

operator!=

Compare two endpoints for inequality.

operator<

Compare endpoints for ordering.

operator<=

Compare endpoints for ordering.

operator==

Compare two endpoints for equality.

operator>

Compare endpoints for ordering.

operator>=

Compare endpoints for ordering.

Related Functions

Name

Description

operator<<

Output an endpoint as a string.

The ip::basic_endpoint class template describes an endpoint that may be associated with a particular socket.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/ip/udp.hpp

Convenience header: boost/asio.hpp

Obtain an identifier for the protocol family.

int family() const;

Compare two protocols for inequality.

friend bool operator!=(
    const udp & p1,
    const udp & p2);
Requirements

Header: boost/asio/ip/udp.hpp

Convenience header: boost/asio.hpp

Compare two protocols for equality.

friend bool operator==(
    const udp & p1,
    const udp & p2);
Requirements

Header: boost/asio/ip/udp.hpp

Convenience header: boost/asio.hpp

Obtain an identifier for the protocol.

int protocol() const;

The UDP resolver type.

typedef basic_resolver< udp > resolver;
Types

Name

Description

endpoint_type

The endpoint type.

implementation_type

The underlying implementation type of I/O object.

iterator

The iterator type.

protocol_type

The protocol type.

query

The query type.

service_type

The type of the service that will be used to provide I/O operations.

Member Functions

Name

Description

async_resolve

Asynchronously perform forward resolution of a query to a list of entries.

Asynchronously perform reverse resolution of an endpoint to a list of entries.

basic_resolver

Constructor.

cancel

Cancel any asynchronous operations that are waiting on the resolver.

get_io_service

Get the io_service associated with the object.

resolve

Perform forward resolution of a query to a list of entries.

Perform reverse resolution of an endpoint to a list of entries.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The ip::basic_resolver class template provides the ability to resolve a query to a list of endpoints.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/ip/udp.hpp

Convenience header: boost/asio.hpp

The UDP socket type.

typedef basic_datagram_socket< udp > socket;
Types

Name

Description

broadcast

Socket option to permit sending of broadcast messages.

bytes_readable

IO control command to get the amount of data that can be read without blocking.

debug

Socket option to enable socket-level debugging.

do_not_route

Socket option to prevent routing, use local interfaces only.

enable_connection_aborted

Socket option to report aborted connections on accept.

endpoint_type

The endpoint type.

implementation_type

The underlying implementation type of I/O object.

keep_alive

Socket option to send keep-alives.

linger

Socket option to specify whether the socket lingers on close if unsent data is present.

lowest_layer_type

A basic_socket is always the lowest layer.

message_flags

Bitmask type for flags that can be passed to send and receive operations.

native_handle_type

The native representation of a socket.

native_type

(Deprecated: Use native_handle_type.) The native representation of a socket.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

protocol_type

The protocol type.

receive_buffer_size

Socket option for the receive buffer size of a socket.

receive_low_watermark

Socket option for the receive low watermark.

reuse_address

Socket option to allow the socket to be bound to an address that is already in use.

send_buffer_size

Socket option for the send buffer size of a socket.

send_low_watermark

Socket option for the send low watermark.

service_type

The type of the service that will be used to provide I/O operations.

shutdown_type

Different ways a socket may be shutdown.

Member Functions

Name

Description

assign

Assign an existing native socket to the socket.

async_connect

Start an asynchronous connect.

async_receive

Start an asynchronous receive on a connected socket.

async_receive_from

Start an asynchronous receive.

async_send

Start an asynchronous send on a connected socket.

async_send_to

Start an asynchronous send.

at_mark

Determine whether the socket is at the out-of-band data mark.

available

Determine the number of bytes available for reading.

basic_datagram_socket

Construct a basic_datagram_socket without opening it.

Construct and open a basic_datagram_socket.

Construct a basic_datagram_socket, opening it and binding it to the given local endpoint.

Construct a basic_datagram_socket on an existing native socket.

Move-construct a basic_datagram_socket from another.

Move-construct a basic_datagram_socket from a socket of another protocol type.

bind

Bind the socket to the given local endpoint.

cancel

Cancel all asynchronous operations associated with the socket.

close

Close the socket.

connect

Connect the socket to the specified endpoint.

get_io_service

Get the io_service associated with the object.

get_option

Get an option from the socket.

io_control

Perform an IO control command on the socket.

is_open

Determine whether the socket is open.

local_endpoint

Get the local endpoint of the socket.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native socket representation.

native_handle

Get the native socket representation.

native_non_blocking

Gets the non-blocking mode of the native socket implementation.

Sets the non-blocking mode of the native socket implementation.

non_blocking

Gets the non-blocking mode of the socket.

Sets the non-blocking mode of the socket.

open

Open the socket using the specified protocol.

operator=

Move-assign a basic_datagram_socket from another.

Move-assign a basic_datagram_socket from a socket of another protocol type.

receive

Receive some data on a connected socket.

receive_from

Receive a datagram with the endpoint of the sender.

remote_endpoint

Get the remote endpoint of the socket.

send

Send some data on a connected socket.

send_to

Send a datagram to the specified endpoint.

set_option

Set an option on the socket.

shutdown

Disable sends or receives on the socket.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Data Members

Name

Description

max_connections

The maximum length of the queue of pending incoming connections.

message_do_not_route

Specify that the data should not be subject to routing.

message_end_of_record

Specifies that the data marks the end of a record.

message_out_of_band

Process out-of-band data.

message_peek

Peek at incoming data without removing it from the input queue.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_datagram_socket class template provides asynchronous and blocking datagram-oriented socket functionality.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/ip/udp.hpp

Convenience header: boost/asio.hpp

Obtain an identifier for the type of the protocol.

int type() const;

Construct to represent the IPv4 UDP protocol.

static udp v4();

Construct to represent the IPv6 UDP protocol.

static udp v6();

Socket option for time-to-live associated with outgoing unicast packets.

typedef implementation_defined hops;

Implements the IPPROTO_IP/IP_UNICAST_TTL socket option.

Examples

Setting the option:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::ip::unicast::hops option(4);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::ip::unicast::hops option;
socket.get_option(option);
int ttl = option.value();
Requirements

Header: boost/asio/ip/unicast.hpp

Convenience header: boost/asio.hpp

Socket option for determining whether an IPv6 socket supports IPv6 communication only.

typedef implementation_defined v6_only;

Implements the IPPROTO_IPV6/IP_V6ONLY socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::v6_only option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::ip::v6_only option;
socket.get_option(option);
bool v6_only = option.value();
Requirements

Header: boost/asio/ip/v6_only.hpp

Convenience header: boost/asio.hpp

Type trait used to determine whether a type can be used as a match condition function with read_until and async_read_until.

template<
    typename T>
struct is_match_condition
Data Members

Name

Description

value

The value member is true if the type may be used as a match condition.

Requirements

Header: boost/asio/read_until.hpp

Convenience header: boost/asio.hpp

The value member is true if the type may be used as a match condition.

static const bool value;

The is_read_buffered class is a traits class that may be used to determine whether a stream type supports buffering of read data.

template<
    typename Stream>
class is_read_buffered
Data Members

Name

Description

value

The value member is true only if the Stream type supports buffering of read data.

Requirements

Header: boost/asio/is_read_buffered.hpp

Convenience header: boost/asio.hpp

The value member is true only if the Stream type supports buffering of read data.

static const bool value;

The is_write_buffered class is a traits class that may be used to determine whether a stream type supports buffering of written data.

template<
    typename Stream>
class is_write_buffered
Data Members

Name

Description

value

The value member is true only if the Stream type supports buffering of written data.

Requirements

Header: boost/asio/is_write_buffered.hpp

Convenience header: boost/asio.hpp

The value member is true only if the Stream type supports buffering of written data.

static const bool value;

Describes an endpoint for a UNIX socket.

template<
    typename Protocol>
class basic_endpoint
Types

Name

Description

data_type

The type of the endpoint structure. This type is dependent on the underlying implementation of the socket layer.

protocol_type

The protocol type associated with the endpoint.

Member Functions

Name

Description

basic_endpoint

Default constructor.

Construct an endpoint using the specified path name.

Copy constructor.

capacity

Get the capacity of the endpoint in the native type.

data

Get the underlying endpoint in the native type.

operator=

Assign from another endpoint.

path

Get the path associated with the endpoint.

Set the path associated with the endpoint.

protocol

The protocol associated with the endpoint.

resize

Set the underlying size of the endpoint in the native type.

size

Get the underlying size of the endpoint in the native type.

Friends

Name

Description

operator!=

Compare two endpoints for inequality.

operator<

Compare endpoints for ordering.

operator<=

Compare endpoints for ordering.

operator==

Compare two endpoints for equality.

operator>

Compare endpoints for ordering.

operator>=

Compare endpoints for ordering.

Related Functions

Name

Description

operator<<

Output an endpoint as a string.

The local::basic_endpoint class template describes an endpoint that may be associated with a particular UNIX socket.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/local/basic_endpoint.hpp

Convenience header: boost/asio.hpp

Default constructor.

basic_endpoint();
  » more...

Construct an endpoint using the specified path name.

basic_endpoint(
    const char * path_name);
  » more...

basic_endpoint(
    const std::string & path_name);
  » more...

Copy constructor.

basic_endpoint(
    const basic_endpoint & other);
  » more...

Default constructor.

basic_endpoint();

Construct an endpoint using the specified path name.

basic_endpoint(
    const char * path_name);

Construct an endpoint using the specified path name.

basic_endpoint(
    const std::string & path_name);

Copy constructor.

basic_endpoint(
    const basic_endpoint & other);

Get the capacity of the endpoint in the native type.

std::size_t capacity() const;

Get the underlying endpoint in the native type.

data_type * data();
  » more...

const data_type * data() const;
  » more...

Get the underlying endpoint in the native type.

data_type * data();

Get the underlying endpoint in the native type.

const data_type * data() const;

The type of the endpoint structure. This type is dependent on the underlying implementation of the socket layer.

typedef implementation_defined data_type;
Requirements

Header: boost/asio/local/basic_endpoint.hpp

Convenience header: boost/asio.hpp

Compare two endpoints for inequality.

friend bool operator!=(
    const basic_endpoint< Protocol > & e1,
    const basic_endpoint< Protocol > & e2);
Requirements

Header: boost/asio/local/basic_endpoint.hpp

Convenience header: boost/asio.hpp

Compare endpoints for ordering.

friend bool operator<(
    const basic_endpoint< Protocol > & e1,
    const basic_endpoint< Protocol > & e2);
Requirements

Header: boost/asio/local/basic_endpoint.hpp

Convenience header: boost/asio.hpp

Output an endpoint as a string.

std::basic_ostream< Elem, Traits > & operator<<(
    std::basic_ostream< Elem, Traits > & os,
    const basic_endpoint< Protocol > & endpoint);

Used to output a human-readable string for a specified endpoint.

Parameters

os

The output stream to which the string will be written.

endpoint

The endpoint to be written.

Return Value

The output stream.

Compare endpoints for ordering.

friend bool operator<=(
    const basic_endpoint< Protocol > & e1,
    const basic_endpoint< Protocol > & e2);
Requirements

Header: boost/asio/local/basic_endpoint.hpp

Convenience header: boost/asio.hpp

Assign from another endpoint.

basic_endpoint & operator=(
    const basic_endpoint & other);

Compare two endpoints for equality.

friend bool operator==(
    const basic_endpoint< Protocol > & e1,
    const basic_endpoint< Protocol > & e2);
Requirements

Header: boost/asio/local/basic_endpoint.hpp

Convenience header: boost/asio.hpp

Compare endpoints for ordering.

friend bool operator>(
    const basic_endpoint< Protocol > & e1,
    const basic_endpoint< Protocol > & e2);
Requirements

Header: boost/asio/local/basic_endpoint.hpp

Convenience header: boost/asio.hpp

Compare endpoints for ordering.

friend bool operator>=(
    const basic_endpoint< Protocol > & e1,
    const basic_endpoint< Protocol > & e2);
Requirements

Header: boost/asio/local/basic_endpoint.hpp

Convenience header: boost/asio.hpp

Get the path associated with the endpoint.

std::string path() const;
  » more...

Set the path associated with the endpoint.

void path(
    const char * p);
  » more...

void path(
    const std::string & p);
  » more...

Get the path associated with the endpoint.

std::string path() const;

Set the path associated with the endpoint.

void path(
    const char * p);

Set the path associated with the endpoint.

void path(
    const std::string & p);

The protocol associated with the endpoint.

protocol_type protocol() const;

The protocol type associated with the endpoint.

typedef Protocol protocol_type;
Requirements

Header: boost/asio/local/basic_endpoint.hpp

Convenience header: boost/asio.hpp

Set the underlying size of the endpoint in the native type.

void resize(
    std::size_t new_size);

Get the underlying size of the endpoint in the native type.

std::size_t size() const;

Create a pair of connected sockets.

template<
    typename Protocol,
    typename SocketService1,
    typename SocketService2>
void connect_pair(
    basic_socket< Protocol, SocketService1 > & socket1,
    basic_socket< Protocol, SocketService2 > & socket2);
  » more...

template<
    typename Protocol,
    typename SocketService1,
    typename SocketService2>
boost::system::error_code connect_pair(
    basic_socket< Protocol, SocketService1 > & socket1,
    basic_socket< Protocol, SocketService2 > & socket2,
    boost::system::error_code & ec);
  » more...
Requirements

Header: boost/asio/local/connect_pair.hpp

Convenience header: boost/asio.hpp

Create a pair of connected sockets.

template<
    typename Protocol,
    typename SocketService1,
    typename SocketService2>
void connect_pair(
    basic_socket< Protocol, SocketService1 > & socket1,
    basic_socket< Protocol, SocketService2 > & socket2);

Create a pair of connected sockets.

template<
    typename Protocol,
    typename SocketService1,
    typename SocketService2>
boost::system::error_code connect_pair(
    basic_socket< Protocol, SocketService1 > & socket1,
    basic_socket< Protocol, SocketService2 > & socket2,
    boost::system::error_code & ec);

Encapsulates the flags needed for datagram-oriented UNIX sockets.

class datagram_protocol
Types

Name

Description

endpoint

The type of a UNIX domain endpoint.

socket

The UNIX domain socket type.

Member Functions

Name

Description

family

Obtain an identifier for the protocol family.

protocol

Obtain an identifier for the protocol.

type

Obtain an identifier for the type of the protocol.

The local::datagram_protocol class contains flags necessary for datagram-oriented UNIX domain sockets.

Thread Safety

Distinct objects: Safe.

Shared objects: Safe.

Requirements

Header: boost/asio/local/datagram_protocol.hpp

Convenience header: boost/asio.hpp

The type of a UNIX domain endpoint.

typedef basic_endpoint< datagram_protocol > endpoint;
Types

Name

Description

data_type

The type of the endpoint structure. This type is dependent on the underlying implementation of the socket layer.

protocol_type

The protocol type associated with the endpoint.

Member Functions

Name

Description

basic_endpoint

Default constructor.

Construct an endpoint using the specified path name.

Copy constructor.

capacity

Get the capacity of the endpoint in the native type.

data

Get the underlying endpoint in the native type.

operator=

Assign from another endpoint.

path

Get the path associated with the endpoint.

Set the path associated with the endpoint.

protocol

The protocol associated with the endpoint.

resize

Set the underlying size of the endpoint in the native type.

size

Get the underlying size of the endpoint in the native type.

Friends

Name

Description

operator!=

Compare two endpoints for inequality.

operator<

Compare endpoints for ordering.

operator<=

Compare endpoints for ordering.

operator==

Compare two endpoints for equality.

operator>

Compare endpoints for ordering.

operator>=

Compare endpoints for ordering.

Related Functions

Name

Description

operator<<

Output an endpoint as a string.

The local::basic_endpoint class template describes an endpoint that may be associated with a particular UNIX socket.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/local/datagram_protocol.hpp

Convenience header: boost/asio.hpp

Obtain an identifier for the protocol family.

int family() const;

Obtain an identifier for the protocol.

int protocol() const;

The UNIX domain socket type.

typedef basic_datagram_socket< datagram_protocol > socket;
Types

Name

Description

broadcast

Socket option to permit sending of broadcast messages.

bytes_readable

IO control command to get the amount of data that can be read without blocking.

debug

Socket option to enable socket-level debugging.

do_not_route

Socket option to prevent routing, use local interfaces only.

enable_connection_aborted

Socket option to report aborted connections on accept.

endpoint_type

The endpoint type.

implementation_type

The underlying implementation type of I/O object.

keep_alive

Socket option to send keep-alives.

linger

Socket option to specify whether the socket lingers on close if unsent data is present.

lowest_layer_type

A basic_socket is always the lowest layer.

message_flags

Bitmask type for flags that can be passed to send and receive operations.

native_handle_type

The native representation of a socket.

native_type

(Deprecated: Use native_handle_type.) The native representation of a socket.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

protocol_type

The protocol type.

receive_buffer_size

Socket option for the receive buffer size of a socket.

receive_low_watermark

Socket option for the receive low watermark.

reuse_address

Socket option to allow the socket to be bound to an address that is already in use.

send_buffer_size

Socket option for the send buffer size of a socket.

send_low_watermark

Socket option for the send low watermark.

service_type

The type of the service that will be used to provide I/O operations.

shutdown_type

Different ways a socket may be shutdown.

Member Functions

Name

Description

assign

Assign an existing native socket to the socket.

async_connect

Start an asynchronous connect.

async_receive

Start an asynchronous receive on a connected socket.

async_receive_from

Start an asynchronous receive.

async_send

Start an asynchronous send on a connected socket.

async_send_to

Start an asynchronous send.

at_mark

Determine whether the socket is at the out-of-band data mark.

available

Determine the number of bytes available for reading.

basic_datagram_socket

Construct a basic_datagram_socket without opening it.

Construct and open a basic_datagram_socket.

Construct a basic_datagram_socket, opening it and binding it to the given local endpoint.

Construct a basic_datagram_socket on an existing native socket.

Move-construct a basic_datagram_socket from another.

Move-construct a basic_datagram_socket from a socket of another protocol type.

bind

Bind the socket to the given local endpoint.

cancel

Cancel all asynchronous operations associated with the socket.

close

Close the socket.

connect

Connect the socket to the specified endpoint.

get_io_service

Get the io_service associated with the object.

get_option

Get an option from the socket.

io_control

Perform an IO control command on the socket.

is_open

Determine whether the socket is open.

local_endpoint

Get the local endpoint of the socket.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native socket representation.

native_handle

Get the native socket representation.

native_non_blocking

Gets the non-blocking mode of the native socket implementation.

Sets the non-blocking mode of the native socket implementation.

non_blocking

Gets the non-blocking mode of the socket.

Sets the non-blocking mode of the socket.

open

Open the socket using the specified protocol.

operator=

Move-assign a basic_datagram_socket from another.

Move-assign a basic_datagram_socket from a socket of another protocol type.

receive

Receive some data on a connected socket.

receive_from

Receive a datagram with the endpoint of the sender.

remote_endpoint

Get the remote endpoint of the socket.

send

Send some data on a connected socket.

send_to

Send a datagram to the specified endpoint.

set_option

Set an option on the socket.

shutdown

Disable sends or receives on the socket.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Data Members

Name

Description

max_connections

The maximum length of the queue of pending incoming connections.

message_do_not_route

Specify that the data should not be subject to routing.

message_end_of_record

Specifies that the data marks the end of a record.

message_out_of_band

Process out-of-band data.

message_peek

Peek at incoming data without removing it from the input queue.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_datagram_socket class template provides asynchronous and blocking datagram-oriented socket functionality.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/local/datagram_protocol.hpp

Convenience header: boost/asio.hpp

Obtain an identifier for the type of the protocol.

int type() const;

Encapsulates the flags needed for stream-oriented UNIX sockets.

class stream_protocol
Types

Name

Description

acceptor

The UNIX domain acceptor type.

endpoint

The type of a UNIX domain endpoint.

iostream

The UNIX domain iostream type.

socket

The UNIX domain socket type.

Member Functions

Name

Description

family

Obtain an identifier for the protocol family.

protocol

Obtain an identifier for the protocol.

type

Obtain an identifier for the type of the protocol.

The local::stream_protocol class contains flags necessary for stream-oriented UNIX domain sockets.

Thread Safety

Distinct objects: Safe.

Shared objects: Safe.

Requirements

Header: boost/asio/local/stream_protocol.hpp

Convenience header: boost/asio.hpp

The UNIX domain acceptor type.

typedef basic_socket_acceptor< stream_protocol > acceptor;
Types

Name

Description

broadcast

Socket option to permit sending of broadcast messages.

bytes_readable

IO control command to get the amount of data that can be read without blocking.

debug

Socket option to enable socket-level debugging.

do_not_route

Socket option to prevent routing, use local interfaces only.

enable_connection_aborted

Socket option to report aborted connections on accept.

endpoint_type

The endpoint type.

implementation_type

The underlying implementation type of I/O object.

keep_alive

Socket option to send keep-alives.

linger

Socket option to specify whether the socket lingers on close if unsent data is present.

message_flags

Bitmask type for flags that can be passed to send and receive operations.

native_handle_type

The native representation of an acceptor.

native_type

(Deprecated: Use native_handle_type.) The native representation of an acceptor.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

protocol_type

The protocol type.

receive_buffer_size

Socket option for the receive buffer size of a socket.

receive_low_watermark

Socket option for the receive low watermark.

reuse_address

Socket option to allow the socket to be bound to an address that is already in use.

send_buffer_size

Socket option for the send buffer size of a socket.

send_low_watermark

Socket option for the send low watermark.

service_type

The type of the service that will be used to provide I/O operations.

shutdown_type

Different ways a socket may be shutdown.

Member Functions

Name

Description

accept

Accept a new connection.

Accept a new connection and obtain the endpoint of the peer.

assign

Assigns an existing native acceptor to the acceptor.

async_accept

Start an asynchronous accept.

basic_socket_acceptor

Construct an acceptor without opening it.

Construct an open acceptor.

Construct an acceptor opened on the given endpoint.

Construct a basic_socket_acceptor on an existing native acceptor.

Move-construct a basic_socket_acceptor from another.

Move-construct a basic_socket_acceptor from an acceptor of another protocol type.

bind

Bind the acceptor to the given local endpoint.

cancel

Cancel all asynchronous operations associated with the acceptor.

close

Close the acceptor.

get_io_service

Get the io_service associated with the object.

get_option

Get an option from the acceptor.

io_control

Perform an IO control command on the acceptor.

is_open

Determine whether the acceptor is open.

listen

Place the acceptor into the state where it will listen for new connections.

local_endpoint

Get the local endpoint of the acceptor.

native

(Deprecated: Use native_handle().) Get the native acceptor representation.

native_handle

Get the native acceptor representation.

native_non_blocking

Gets the non-blocking mode of the native acceptor implementation.

Sets the non-blocking mode of the native acceptor implementation.

non_blocking

Gets the non-blocking mode of the acceptor.

Sets the non-blocking mode of the acceptor.

open

Open the acceptor using the specified protocol.

operator=

Move-assign a basic_socket_acceptor from another.

Move-assign a basic_socket_acceptor from an acceptor of another protocol type.

set_option

Set an option on the acceptor.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Data Members

Name

Description

max_connections

The maximum length of the queue of pending incoming connections.

message_do_not_route

Specify that the data should not be subject to routing.

message_end_of_record

Specifies that the data marks the end of a record.

message_out_of_band

Process out-of-band data.

message_peek

Peek at incoming data without removing it from the input queue.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_socket_acceptor class template is used for accepting new socket connections.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Example

Opening a socket acceptor with the SO_REUSEADDR option enabled:

boost::asio::ip::tcp::acceptor acceptor(io_service);
boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), port);
acceptor.open(endpoint.protocol());
acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor.bind(endpoint);
acceptor.listen();
Requirements

Header: boost/asio/local/stream_protocol.hpp

Convenience header: boost/asio.hpp

The type of a UNIX domain endpoint.

typedef basic_endpoint< stream_protocol > endpoint;
Types

Name

Description

data_type

The type of the endpoint structure. This type is dependent on the underlying implementation of the socket layer.

protocol_type

The protocol type associated with the endpoint.

Member Functions

Name

Description

basic_endpoint

Default constructor.

Construct an endpoint using the specified path name.

Copy constructor.

capacity

Get the capacity of the endpoint in the native type.

data

Get the underlying endpoint in the native type.

operator=

Assign from another endpoint.

path

Get the path associated with the endpoint.

Set the path associated with the endpoint.

protocol

The protocol associated with the endpoint.

resize

Set the underlying size of the endpoint in the native type.

size

Get the underlying size of the endpoint in the native type.

Friends

Name

Description

operator!=

Compare two endpoints for inequality.

operator<

Compare endpoints for ordering.

operator<=

Compare endpoints for ordering.

operator==

Compare two endpoints for equality.

operator>

Compare endpoints for ordering.

operator>=

Compare endpoints for ordering.

Related Functions

Name

Description

operator<<

Output an endpoint as a string.

The local::basic_endpoint class template describes an endpoint that may be associated with a particular UNIX socket.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/local/stream_protocol.hpp

Convenience header: boost/asio.hpp

Obtain an identifier for the protocol family.

int family() const;

The UNIX domain iostream type.

typedef basic_socket_iostream< stream_protocol > iostream;
Types

Name

Description

duration_type

The duration type.

endpoint_type

The endpoint type.

time_type

The time type.

Member Functions

Name

Description

basic_socket_iostream

Construct a basic_socket_iostream without establishing a connection.

Establish a connection to an endpoint corresponding to a resolver query.

close

Close the connection.

connect

Establish a connection to an endpoint corresponding to a resolver query.

error

Get the last error associated with the stream.

expires_at

Get the stream's expiry time as an absolute time.

Set the stream's expiry time as an absolute time.

expires_from_now

Get the timer's expiry time relative to now.

Set the stream's expiry time relative to now.

rdbuf

Return a pointer to the underlying streambuf.

Requirements

Header: boost/asio/local/stream_protocol.hpp

Convenience header: boost/asio.hpp

Obtain an identifier for the protocol.

int protocol() const;

The UNIX domain socket type.

typedef basic_stream_socket< stream_protocol > socket;
Types

Name

Description

broadcast

Socket option to permit sending of broadcast messages.

bytes_readable

IO control command to get the amount of data that can be read without blocking.

debug

Socket option to enable socket-level debugging.

do_not_route

Socket option to prevent routing, use local interfaces only.

enable_connection_aborted

Socket option to report aborted connections on accept.

endpoint_type

The endpoint type.

implementation_type

The underlying implementation type of I/O object.

keep_alive

Socket option to send keep-alives.

linger

Socket option to specify whether the socket lingers on close if unsent data is present.

lowest_layer_type

A basic_socket is always the lowest layer.

message_flags

Bitmask type for flags that can be passed to send and receive operations.

native_handle_type

The native representation of a socket.

native_type

(Deprecated: Use native_handle_type.) The native representation of a socket.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

protocol_type

The protocol type.

receive_buffer_size

Socket option for the receive buffer size of a socket.

receive_low_watermark

Socket option for the receive low watermark.

reuse_address

Socket option to allow the socket to be bound to an address that is already in use.

send_buffer_size

Socket option for the send buffer size of a socket.

send_low_watermark

Socket option for the send low watermark.

service_type

The type of the service that will be used to provide I/O operations.

shutdown_type

Different ways a socket may be shutdown.

Member Functions

Name

Description

assign

Assign an existing native socket to the socket.

async_connect

Start an asynchronous connect.

async_read_some

Start an asynchronous read.

async_receive

Start an asynchronous receive.

async_send

Start an asynchronous send.

async_write_some

Start an asynchronous write.

at_mark

Determine whether the socket is at the out-of-band data mark.

available

Determine the number of bytes available for reading.

basic_stream_socket

Construct a basic_stream_socket without opening it.

Construct and open a basic_stream_socket.

Construct a basic_stream_socket, opening it and binding it to the given local endpoint.

Construct a basic_stream_socket on an existing native socket.

Move-construct a basic_stream_socket from another.

Move-construct a basic_stream_socket from a socket of another protocol type.

bind

Bind the socket to the given local endpoint.

cancel

Cancel all asynchronous operations associated with the socket.

close

Close the socket.

connect

Connect the socket to the specified endpoint.

get_io_service

Get the io_service associated with the object.

get_option

Get an option from the socket.

io_control

Perform an IO control command on the socket.

is_open

Determine whether the socket is open.

local_endpoint

Get the local endpoint of the socket.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native socket representation.

native_handle

Get the native socket representation.

native_non_blocking

Gets the non-blocking mode of the native socket implementation.

Sets the non-blocking mode of the native socket implementation.

non_blocking

Gets the non-blocking mode of the socket.

Sets the non-blocking mode of the socket.

open

Open the socket using the specified protocol.

operator=

Move-assign a basic_stream_socket from another.

Move-assign a basic_stream_socket from a socket of another protocol type.

read_some

Read some data from the socket.

receive

Receive some data on the socket.

Receive some data on a connected socket.

remote_endpoint

Get the remote endpoint of the socket.

send

Send some data on the socket.

set_option

Set an option on the socket.

shutdown

Disable sends or receives on the socket.

write_some

Write some data to the socket.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Data Members

Name

Description

max_connections

The maximum length of the queue of pending incoming connections.

message_do_not_route

Specify that the data should not be subject to routing.

message_end_of_record

Specifies that the data marks the end of a record.

message_out_of_band

Process out-of-band data.

message_peek

Peek at incoming data without removing it from the input queue.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_stream_socket class template provides asynchronous and blocking stream-oriented socket functionality.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/local/stream_protocol.hpp

Convenience header: boost/asio.hpp

Obtain an identifier for the type of the protocol.

int type() const;

Holds a buffer that can be modified.

class mutable_buffer
Member Functions

Name

Description

mutable_buffer

Construct an empty buffer.

Construct a buffer to represent a given memory range.

Related Functions

Name

Description

operator+

Create a new modifiable buffer that is offset from the start of another.

The mutable_buffer class provides a safe representation of a buffer that can be modified. It does not own the underlying data, and so is cheap to copy or assign.

Accessing Buffer Contents

The contents of a buffer may be accessed using the buffer_size and buffer_cast functions:

boost::asio::mutable_buffer b1 = ...;
std::size_t s1 = boost::asio::buffer_size(b1);
unsigned char* p1 = boost::asio::buffer_cast<unsigned char*>(b1);

The boost::asio::buffer_cast function permits violations of type safety, so uses of it in application code should be carefully considered.

Requirements

Header: boost/asio/buffer.hpp

Convenience header: boost/asio.hpp

Construct an empty buffer.

mutable_buffer();
  » more...

Construct a buffer to represent a given memory range.

mutable_buffer(
    void * data,
    std::size_t size);
  » more...

Construct an empty buffer.

mutable_buffer();

Construct a buffer to represent a given memory range.

mutable_buffer(
    void * data,
    std::size_t size);

Create a new modifiable buffer that is offset from the start of another.

mutable_buffer operator+(
    const mutable_buffer & b,
    std::size_t start);
  » more...

mutable_buffer operator+(
    std::size_t start,
    const mutable_buffer & b);
  » more...

Create a new modifiable buffer that is offset from the start of another.

mutable_buffer operator+(
    const mutable_buffer & b,
    std::size_t start);

Create a new modifiable buffer that is offset from the start of another.

mutable_buffer operator+(
    std::size_t start,
    const mutable_buffer & b);

Adapts a single modifiable buffer so that it meets the requirements of the MutableBufferSequence concept.

class mutable_buffers_1 :
  public mutable_buffer
Types

Name

Description

const_iterator

A random-access iterator type that may be used to read elements.

value_type

The type for each element in the list of buffers.

Member Functions

Name

Description

begin

Get a random-access iterator to the first element.

end

Get a random-access iterator for one past the last element.

mutable_buffers_1

Construct to represent a given memory range.

Construct to represent a single modifiable buffer.

Related Functions

Name

Description

operator+

Create a new modifiable buffer that is offset from the start of another.

Requirements

Header: boost/asio/buffer.hpp

Convenience header: boost/asio.hpp

Get a random-access iterator to the first element.

const_iterator begin() const;

A random-access iterator type that may be used to read elements.

typedef const mutable_buffer * const_iterator;
Requirements

Header: boost/asio/buffer.hpp

Convenience header: boost/asio.hpp

Get a random-access iterator for one past the last element.

const_iterator end() const;

Construct to represent a given memory range.

mutable_buffers_1(
    void * data,
    std::size_t size);
  » more...

Construct to represent a single modifiable buffer.

explicit mutable_buffers_1(
    const mutable_buffer & b);
  » more...

Construct to represent a given memory range.

mutable_buffers_1(
    void * data,
    std::size_t size);

Construct to represent a single modifiable buffer.

mutable_buffers_1(
    const mutable_buffer & b);

Create a new modifiable buffer that is offset from the start of another.

mutable_buffer operator+(
    const mutable_buffer & b,
    std::size_t start);
  » more...

mutable_buffer operator+(
    std::size_t start,
    const mutable_buffer & b);
  » more...

Inherited from mutable_buffer.

Create a new modifiable buffer that is offset from the start of another.

mutable_buffer operator+(
    const mutable_buffer & b,
    std::size_t start);

Inherited from mutable_buffer.

Create a new modifiable buffer that is offset from the start of another.

mutable_buffer operator+(
    std::size_t start,
    const mutable_buffer & b);

The type for each element in the list of buffers.

typedef mutable_buffer value_type;
Member Functions

Name

Description

mutable_buffer

Construct an empty buffer.

Construct a buffer to represent a given memory range.

Related Functions

Name

Description

operator+

Create a new modifiable buffer that is offset from the start of another.

The mutable_buffer class provides a safe representation of a buffer that can be modified. It does not own the underlying data, and so is cheap to copy or assign.

Accessing Buffer Contents

The contents of a buffer may be accessed using the buffer_size and buffer_cast functions:

boost::asio::mutable_buffer b1 = ...;
std::size_t s1 = boost::asio::buffer_size(b1);
unsigned char* p1 = boost::asio::buffer_cast<unsigned char*>(b1);

The boost::asio::buffer_cast function permits violations of type safety, so uses of it in application code should be carefully considered.

Requirements

Header: boost/asio/buffer.hpp

Convenience header: boost/asio.hpp

An implementation of both the ConstBufferSequence and MutableBufferSequence concepts to represent a null buffer sequence.

class null_buffers
Types

Name

Description

const_iterator

A random-access iterator type that may be used to read elements.

value_type

The type for each element in the list of buffers.

Member Functions

Name

Description

begin

Get a random-access iterator to the first element.

end

Get a random-access iterator for one past the last element.

Requirements

Header: boost/asio/buffer.hpp

Convenience header: boost/asio.hpp

Get a random-access iterator to the first element.

const_iterator begin() const;

A random-access iterator type that may be used to read elements.

typedef const mutable_buffer * const_iterator;
Requirements

Header: boost/asio/buffer.hpp

Convenience header: boost/asio.hpp

Get a random-access iterator for one past the last element.

const_iterator end() const;

The type for each element in the list of buffers.

typedef mutable_buffer value_type;
Member Functions

Name

Description

mutable_buffer

Construct an empty buffer.

Construct a buffer to represent a given memory range.

Related Functions

Name

Description

operator+

Create a new modifiable buffer that is offset from the start of another.

The mutable_buffer class provides a safe representation of a buffer that can be modified. It does not own the underlying data, and so is cheap to copy or assign.

Accessing Buffer Contents

The contents of a buffer may be accessed using the buffer_size and buffer_cast functions:

boost::asio::mutable_buffer b1 = ...;
std::size_t s1 = boost::asio::buffer_size(b1);
unsigned char* p1 = boost::asio::buffer_cast<unsigned char*>(b1);

The boost::asio::buffer_cast function permits violations of type safety, so uses of it in application code should be carefully considered.

Requirements

Header: boost/asio/buffer.hpp

Convenience header: boost/asio.hpp

An argument placeholder, for use with boost::bind(), that corresponds to the bytes_transferred argument of a handler for asynchronous functions such as boost::asio::basic_stream_socket::async_write_some or boost::asio::async_write.

unspecified bytes_transferred;
Requirements

Header: boost/asio/placeholders.hpp

Convenience header: boost/asio.hpp

An argument placeholder, for use with boost::bind(), that corresponds to the error argument of a handler for any of the asynchronous functions.

unspecified error;
Requirements

Header: boost/asio/placeholders.hpp

Convenience header: boost/asio.hpp

An argument placeholder, for use with boost::bind(), that corresponds to the iterator argument of a handler for asynchronous functions such as boost::asio::basic_resolver::async_resolve.

unspecified iterator;
Requirements

Header: boost/asio/placeholders.hpp

Convenience header: boost/asio.hpp

An argument placeholder, for use with boost::bind(), that corresponds to the signal_number argument of a handler for asynchronous functions such as boost::asio::signal_set::async_wait.

unspecified signal_number;
Requirements

Header: boost/asio/placeholders.hpp

Convenience header: boost/asio.hpp

Provides POSIX descriptor functionality.

template<
    typename DescriptorService>
class basic_descriptor :
  public basic_io_object< DescriptorService >,
  public posix::descriptor_base
Types

Name

Description

bytes_readable

IO control command to get the amount of data that can be read without blocking.

implementation_type

The underlying implementation type of I/O object.

lowest_layer_type

A basic_descriptor is always the lowest layer.

native_handle_type

The native representation of a descriptor.

native_type

(Deprecated: Use native_handle_type.) The native representation of a descriptor.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the descriptor.

service_type

The type of the service that will be used to provide I/O operations.

Member Functions

Name

Description

assign

Assign an existing native descriptor to the descriptor.

basic_descriptor

Construct a basic_descriptor without opening it.

Construct a basic_descriptor on an existing native descriptor.

Move-construct a basic_descriptor from another.

cancel

Cancel all asynchronous operations associated with the descriptor.

close

Close the descriptor.

get_io_service

Get the io_service associated with the object.

io_control

Perform an IO control command on the descriptor.

is_open

Determine whether the descriptor is open.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native descriptor representation.

native_handle

Get the native descriptor representation.

native_non_blocking

Gets the non-blocking mode of the native descriptor implementation.

Sets the non-blocking mode of the native descriptor implementation.

non_blocking

Gets the non-blocking mode of the descriptor.

Sets the non-blocking mode of the descriptor.

operator=

Move-assign a basic_descriptor from another.

release

Release ownership of the native descriptor implementation.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

~basic_descriptor

Protected destructor to prevent deletion through this type.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The posix::basic_descriptor class template provides the ability to wrap a POSIX descriptor.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/posix/basic_descriptor.hpp

Convenience header: boost/asio.hpp

Assign an existing native descriptor to the descriptor.

void assign(
    const native_handle_type & native_descriptor);
  » more...

boost::system::error_code assign(
    const native_handle_type & native_descriptor,
    boost::system::error_code & ec);
  » more...

Assign an existing native descriptor to the descriptor.

void assign(
    const native_handle_type & native_descriptor);

Assign an existing native descriptor to the descriptor.

boost::system::error_code assign(
    const native_handle_type & native_descriptor,
    boost::system::error_code & ec);

Construct a posix::basic_descriptor without opening it.

explicit basic_descriptor(
    boost::asio::io_service & io_service);
  » more...

Construct a posix::basic_descriptor on an existing native descriptor.

basic_descriptor(
    boost::asio::io_service & io_service,
    const native_handle_type & native_descriptor);
  » more...

Move-construct a posix::basic_descriptor from another.

basic_descriptor(
    basic_descriptor && other);
  » more...

Construct a posix::basic_descriptor without opening it.

basic_descriptor(
    boost::asio::io_service & io_service);

This constructor creates a descriptor without opening it.

Parameters

io_service

The io_service object that the descriptor will use to dispatch handlers for any asynchronous operations performed on the descriptor.

Construct a posix::basic_descriptor on an existing native descriptor.

basic_descriptor(
    boost::asio::io_service & io_service,
    const native_handle_type & native_descriptor);

This constructor creates a descriptor object to hold an existing native descriptor.

Parameters

io_service

The io_service object that the descriptor will use to dispatch handlers for any asynchronous operations performed on the descriptor.

native_descriptor

A native descriptor.

Exceptions

boost::system::system_error

Thrown on failure.

Move-construct a posix::basic_descriptor from another.

basic_descriptor(
    basic_descriptor && other);

This constructor moves a descriptor from one object to another.

Parameters

other

The other posix::basic_descriptor object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_descriptor(io_service&) constructor.

Inherited from posix::descriptor_base.

IO control command to get the amount of data that can be read without blocking.

typedef implementation_defined bytes_readable;

Implements the FIONREAD IO control command.

Example
boost::asio::posix::stream_descriptor descriptor(io_service);
...
boost::asio::descriptor_base::bytes_readable command(true);
descriptor.io_control(command);
std::size_t bytes_readable = command.get();
Requirements

Header: boost/asio/posix/basic_descriptor.hpp

Convenience header: boost/asio.hpp

Cancel all asynchronous operations associated with the descriptor.

void cancel();
  » more...

boost::system::error_code cancel(
    boost::system::error_code & ec);
  » more...

Cancel all asynchronous operations associated with the descriptor.

void cancel();

This function causes all outstanding asynchronous read or write operations to finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error.

Exceptions

boost::system::system_error

Thrown on failure.

Cancel all asynchronous operations associated with the descriptor.

boost::system::error_code cancel(
    boost::system::error_code & ec);

This function causes all outstanding asynchronous read or write operations to finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error.

Parameters

ec

Set to indicate what error occurred, if any.

Close the descriptor.

void close();
  » more...

boost::system::error_code close(
    boost::system::error_code & ec);
  » more...

Close the descriptor.

void close();

This function is used to close the descriptor. Any asynchronous read or write operations will be cancelled immediately, and will complete with the boost::asio::error::operation_aborted error.

Exceptions

boost::system::system_error

Thrown on failure. Note that, even if the function indicates an error, the underlying descriptor is closed.

Close the descriptor.

boost::system::error_code close(
    boost::system::error_code & ec);

This function is used to close the descriptor. Any asynchronous read or write operations will be cancelled immediately, and will complete with the boost::asio::error::operation_aborted error.

Parameters

ec

Set to indicate what error occurred, if any. Note that, even if the function indicates an error, the underlying descriptor is closed.

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();
  » more...

const implementation_type & get_implementation() const;
  » more...

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

const implementation_type & get_implementation() const;

Inherited from basic_io_object.

Get the io_service associated with the object.

boost::asio::io_service & get_io_service();

This function may be used to obtain the io_service object that the I/O object uses to dispatch handlers for asynchronous operations.

Return Value

A reference to the io_service object that the I/O object will use to dispatch handlers. Ownership is not transferred to the caller.

Get the service associated with the I/O object.

service_type & get_service();
  » more...

const service_type & get_service() const;
  » more...

Inherited from basic_io_object.

Get the service associated with the I/O object.

service_type & get_service();

Inherited from basic_io_object.

Get the service associated with the I/O object.

const service_type & get_service() const;

Inherited from basic_io_object.

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

implementation_type implementation;

Inherited from basic_io_object.

The underlying implementation type of I/O object.

typedef service_type::implementation_type implementation_type;
Requirements

Header: boost/asio/posix/basic_descriptor.hpp

Convenience header: boost/asio.hpp

Perform an IO control command on the descriptor.

template<
    typename IoControlCommand>
void io_control(
    IoControlCommand & command);
  » more...

template<
    typename IoControlCommand>
boost::system::error_code io_control(
    IoControlCommand & command,
    boost::system::error_code & ec);
  » more...

Perform an IO control command on the descriptor.

template<
    typename IoControlCommand>
void io_control(
    IoControlCommand & command);

This function is used to execute an IO control command on the descriptor.

Parameters

command

The IO control command to be performed on the descriptor.

Exceptions

boost::system::system_error

Thrown on failure.

Example

Getting the number of bytes ready to read:

boost::asio::posix::stream_descriptor descriptor(io_service);
...
boost::asio::posix::stream_descriptor::bytes_readable command;
descriptor.io_control(command);
std::size_t bytes_readable = command.get();

Perform an IO control command on the descriptor.

template<
    typename IoControlCommand>
boost::system::error_code io_control(
    IoControlCommand & command,
    boost::system::error_code & ec);

This function is used to execute an IO control command on the descriptor.

Parameters

command

The IO control command to be performed on the descriptor.

ec

Set to indicate what error occurred, if any.

Example

Getting the number of bytes ready to read:

boost::asio::posix::stream_descriptor descriptor(io_service);
...
boost::asio::posix::stream_descriptor::bytes_readable command;
boost::system::error_code ec;
descriptor.io_control(command, ec);
if (ec)
{
  // An error occurred.
}
std::size_t bytes_readable = command.get();

Determine whether the descriptor is open.

bool is_open() const;

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();
  » more...

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;
  » more...

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();

This function returns a reference to the lowest layer in a stack of layers. Since a posix::basic_descriptor cannot contain any further layers, it simply returns a reference to itself.

Return Value

A reference to the lowest layer in the stack of layers. Ownership is not transferred to the caller.

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;

This function returns a const reference to the lowest layer in a stack of layers. Since a posix::basic_descriptor cannot contain any further layers, it simply returns a reference to itself.

Return Value

A const reference to the lowest layer in the stack of layers. Ownership is not transferred to the caller.

A posix::basic_descriptor is always the lowest layer.

typedef basic_descriptor< DescriptorService > lowest_layer_type;
Types

Name

Description

bytes_readable

IO control command to get the amount of data that can be read without blocking.

implementation_type

The underlying implementation type of I/O object.

lowest_layer_type

A basic_descriptor is always the lowest layer.

native_handle_type

The native representation of a descriptor.

native_type

(Deprecated: Use native_handle_type.) The native representation of a descriptor.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the descriptor.

service_type

The type of the service that will be used to provide I/O operations.

Member Functions

Name

Description

assign

Assign an existing native descriptor to the descriptor.

basic_descriptor

Construct a basic_descriptor without opening it.

Construct a basic_descriptor on an existing native descriptor.

Move-construct a basic_descriptor from another.

cancel

Cancel all asynchronous operations associated with the descriptor.

close

Close the descriptor.

get_io_service

Get the io_service associated with the object.

io_control

Perform an IO control command on the descriptor.

is_open

Determine whether the descriptor is open.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native descriptor representation.

native_handle

Get the native descriptor representation.

native_non_blocking

Gets the non-blocking mode of the native descriptor implementation.

Sets the non-blocking mode of the native descriptor implementation.

non_blocking

Gets the non-blocking mode of the descriptor.

Sets the non-blocking mode of the descriptor.

operator=

Move-assign a basic_descriptor from another.

release

Release ownership of the native descriptor implementation.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

~basic_descriptor

Protected destructor to prevent deletion through this type.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The posix::basic_descriptor class template provides the ability to wrap a POSIX descriptor.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/posix/basic_descriptor.hpp

Convenience header: boost/asio.hpp

(Deprecated: Use native_handle().) Get the native descriptor representation.

native_type native();

This function may be used to obtain the underlying representation of the descriptor. This is intended to allow access to native descriptor functionality that is not otherwise provided.

Get the native descriptor representation.

native_handle_type native_handle();

This function may be used to obtain the underlying representation of the descriptor. This is intended to allow access to native descriptor functionality that is not otherwise provided.

The native representation of a descriptor.

typedef DescriptorService::native_handle_type native_handle_type;
Requirements

Header: boost/asio/posix/basic_descriptor.hpp

Convenience header: boost/asio.hpp

Gets the non-blocking mode of the native descriptor implementation.

bool native_non_blocking() const;
  » more...

Sets the non-blocking mode of the native descriptor implementation.

void native_non_blocking(
    bool mode);
  » more...

boost::system::error_code native_non_blocking(
    bool mode,
    boost::system::error_code & ec);
  » more...

Gets the non-blocking mode of the native descriptor implementation.

bool native_non_blocking() const;

This function is used to retrieve the non-blocking mode of the underlying native descriptor. This mode has no effect on the behaviour of the descriptor object's synchronous operations.

Return Value

true if the underlying descriptor is in non-blocking mode and direct system calls may fail with boost::asio::error::would_block (or the equivalent system error).

Remarks

The current non-blocking mode is cached by the descriptor object. Consequently, the return value may be incorrect if the non-blocking mode was set directly on the native descriptor.

Sets the non-blocking mode of the native descriptor implementation.

void native_non_blocking(
    bool mode);

This function is used to modify the non-blocking mode of the underlying native descriptor. It has no effect on the behaviour of the descriptor object's synchronous operations.

Parameters

mode

If true, the underlying descriptor is put into non-blocking mode and direct system calls may fail with boost::asio::error::would_block (or the equivalent system error).

Exceptions

boost::system::system_error

Thrown on failure. If the mode is false, but the current value of non_blocking() is true, this function fails with boost::asio::error::invalid_argument, as the combination does not make sense.

Sets the non-blocking mode of the native descriptor implementation.

boost::system::error_code native_non_blocking(
    bool mode,
    boost::system::error_code & ec);

This function is used to modify the non-blocking mode of the underlying native descriptor. It has no effect on the behaviour of the descriptor object's synchronous operations.

Parameters

mode

If true, the underlying descriptor is put into non-blocking mode and direct system calls may fail with boost::asio::error::would_block (or the equivalent system error).

ec

Set to indicate what error occurred, if any. If the mode is false, but the current value of non_blocking() is true, this function fails with boost::asio::error::invalid_argument, as the combination does not make sense.

(Deprecated: Use native_handle_type.) The native representation of a descriptor.

typedef DescriptorService::native_handle_type native_type;
Requirements

Header: boost/asio/posix/basic_descriptor.hpp

Convenience header: boost/asio.hpp

Gets the non-blocking mode of the descriptor.

bool non_blocking() const;
  » more...

Sets the non-blocking mode of the descriptor.

void non_blocking(
    bool mode);
  » more...

boost::system::error_code non_blocking(
    bool mode,
    boost::system::error_code & ec);
  » more...

Gets the non-blocking mode of the descriptor.

bool non_blocking() const;
Return Value

true if the descriptor's synchronous operations will fail with boost::asio::error::would_block if they are unable to perform the requested operation immediately. If false, synchronous operations will block until complete.

Remarks

The non-blocking mode has no effect on the behaviour of asynchronous operations. Asynchronous operations will never fail with the error boost::asio::error::would_block.

Sets the non-blocking mode of the descriptor.

void non_blocking(
    bool mode);
Parameters

mode

If true, the descriptor's synchronous operations will fail with boost::asio::error::would_block if they are unable to perform the requested operation immediately. If false, synchronous operations will block until complete.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

The non-blocking mode has no effect on the behaviour of asynchronous operations. Asynchronous operations will never fail with the error boost::asio::error::would_block.

Sets the non-blocking mode of the descriptor.

boost::system::error_code non_blocking(
    bool mode,
    boost::system::error_code & ec);
Parameters

mode

If true, the descriptor's synchronous operations will fail with boost::asio::error::would_block if they are unable to perform the requested operation immediately. If false, synchronous operations will block until complete.

ec

Set to indicate what error occurred, if any.

Remarks

The non-blocking mode has no effect on the behaviour of asynchronous operations. Asynchronous operations will never fail with the error boost::asio::error::would_block.

Inherited from posix::descriptor_base.

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the descriptor.

typedef implementation_defined non_blocking_io;

Implements the FIONBIO IO control command.

Example
boost::asio::posix::stream_descriptor descriptor(io_service);
...
boost::asio::descriptor_base::non_blocking_io command(true);
descriptor.io_control(command);
Requirements

Header: boost/asio/posix/basic_descriptor.hpp

Convenience header: boost/asio.hpp

Move-assign a posix::basic_descriptor from another.

basic_descriptor & operator=(
    basic_descriptor && other);

This assignment operator moves a descriptor from one object to another.

Parameters

other

The other posix::basic_descriptor object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_descriptor(io_service&) constructor.

Release ownership of the native descriptor implementation.

native_handle_type release();

This function may be used to obtain the underlying representation of the descriptor. After calling this function, is_open() returns false. The caller is responsible for closing the descriptor.

All outstanding asynchronous read or write operations will finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error.

Inherited from basic_io_object.

(Deprecated: Use get_service().) The service associated with the I/O object.

service_type & service;
Remarks

Available only for services that do not support movability.

Inherited from basic_io_object.

The type of the service that will be used to provide I/O operations.

typedef DescriptorService service_type;
Requirements

Header: boost/asio/posix/basic_descriptor.hpp

Convenience header: boost/asio.hpp

Protected destructor to prevent deletion through this type.

~basic_descriptor();

Provides stream-oriented descriptor functionality.

template<
    typename StreamDescriptorService = stream_descriptor_service>
class basic_stream_descriptor :
  public posix::basic_descriptor< StreamDescriptorService >
Types

Name

Description

bytes_readable

IO control command to get the amount of data that can be read without blocking.

implementation_type

The underlying implementation type of I/O object.

lowest_layer_type

A basic_descriptor is always the lowest layer.

native_handle_type

The native representation of a descriptor.

native_type

(Deprecated: Use native_handle_type.) The native representation of a descriptor.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the descriptor.

service_type

The type of the service that will be used to provide I/O operations.

Member Functions

Name

Description

assign

Assign an existing native descriptor to the descriptor.

async_read_some

Start an asynchronous read.

async_write_some

Start an asynchronous write.

basic_stream_descriptor

Construct a basic_stream_descriptor without opening it.

Construct a basic_stream_descriptor on an existing native descriptor.

Move-construct a basic_stream_descriptor from another.

cancel

Cancel all asynchronous operations associated with the descriptor.

close

Close the descriptor.

get_io_service

Get the io_service associated with the object.

io_control

Perform an IO control command on the descriptor.

is_open

Determine whether the descriptor is open.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native descriptor representation.

native_handle

Get the native descriptor representation.

native_non_blocking

Gets the non-blocking mode of the native descriptor implementation.

Sets the non-blocking mode of the native descriptor implementation.

non_blocking

Gets the non-blocking mode of the descriptor.

Sets the non-blocking mode of the descriptor.

operator=

Move-assign a basic_stream_descriptor from another.

read_some

Read some data from the descriptor.

release

Release ownership of the native descriptor implementation.

write_some

Write some data to the descriptor.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The posix::basic_stream_descriptor class template provides asynchronous and blocking stream-oriented descriptor functionality.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/posix/basic_stream_descriptor.hpp

Convenience header: boost/asio.hpp

Assign an existing native descriptor to the descriptor.

void assign(
    const native_handle_type & native_descriptor);
  » more...

boost::system::error_code assign(
    const native_handle_type & native_descriptor,
    boost::system::error_code & ec);
  » more...

Inherited from posix::basic_descriptor.

Assign an existing native descriptor to the descriptor.

void assign(
    const native_handle_type & native_descriptor);

Inherited from posix::basic_descriptor.

Assign an existing native descriptor to the descriptor.

boost::system::error_code assign(
    const native_handle_type & native_descriptor,
    boost::system::error_code & ec);

Start an asynchronous read.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_read_some(
    const MutableBufferSequence & buffers,
    ReadHandler handler);

This function is used to asynchronously read data from the stream descriptor. The function call always returns immediately.

Parameters

buffers

One or more buffers into which the data will be read. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

handler

The handler to be called when the read operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes read.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

The read operation may not read all of the requested number of bytes. Consider using the async_read function if you need to ensure that the requested amount of data is read before the asynchronous operation completes.

Example

To read into a single data buffer use the buffer function as follows:

descriptor.async_read_some(boost::asio::buffer(data, size), handler);

See the buffer documentation for information on reading into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Start an asynchronous write.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_write_some(
    const ConstBufferSequence & buffers,
    WriteHandler handler);

This function is used to asynchronously write data to the stream descriptor. The function call always returns immediately.

Parameters

buffers

One or more data buffers to be written to the descriptor. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

handler

The handler to be called when the write operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes written.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

The write operation may not transmit all of the data to the peer. Consider using the async_write function if you need to ensure that all data is written before the asynchronous operation completes.

Example

To write a single data buffer use the buffer function as follows:

descriptor.async_write_some(boost::asio::buffer(data, size), handler);

See the buffer documentation for information on writing multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Construct a posix::basic_stream_descriptor without opening it.

explicit basic_stream_descriptor(
    boost::asio::io_service & io_service);
  » more...

Construct a posix::basic_stream_descriptor on an existing native descriptor.

basic_stream_descriptor(
    boost::asio::io_service & io_service,
    const native_handle_type & native_descriptor);
  » more...

Move-construct a posix::basic_stream_descriptor from another.

basic_stream_descriptor(
    basic_stream_descriptor && other);
  » more...

Construct a posix::basic_stream_descriptor without opening it.

basic_stream_descriptor(
    boost::asio::io_service & io_service);

This constructor creates a stream descriptor without opening it. The descriptor needs to be opened and then connected or accepted before data can be sent or received on it.

Parameters

io_service

The io_service object that the stream descriptor will use to dispatch handlers for any asynchronous operations performed on the descriptor.

Construct a posix::basic_stream_descriptor on an existing native descriptor.

basic_stream_descriptor(
    boost::asio::io_service & io_service,
    const native_handle_type & native_descriptor);

This constructor creates a stream descriptor object to hold an existing native descriptor.

Parameters

io_service

The io_service object that the stream descriptor will use to dispatch handlers for any asynchronous operations performed on the descriptor.

native_descriptor

The new underlying descriptor implementation.

Exceptions

boost::system::system_error

Thrown on failure.

Move-construct a posix::basic_stream_descriptor from another.

basic_stream_descriptor(
    basic_stream_descriptor && other);

This constructor moves a stream descriptor from one object to another.

Parameters

other

The other posix::basic_stream_descriptor object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_stream_descriptor(io_service&) constructor.

Inherited from posix::descriptor_base.

IO control command to get the amount of data that can be read without blocking.

typedef implementation_defined bytes_readable;

Implements the FIONREAD IO control command.

Example
boost::asio::posix::stream_descriptor descriptor(io_service);
...
boost::asio::descriptor_base::bytes_readable command(true);
descriptor.io_control(command);
std::size_t bytes_readable = command.get();
Requirements

Header: boost/asio/posix/basic_stream_descriptor.hpp

Convenience header: boost/asio.hpp

Cancel all asynchronous operations associated with the descriptor.

void cancel();
  » more...

boost::system::error_code cancel(
    boost::system::error_code & ec);
  » more...

Inherited from posix::basic_descriptor.

Cancel all asynchronous operations associated with the descriptor.

void cancel();

This function causes all outstanding asynchronous read or write operations to finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error.

Exceptions

boost::system::system_error

Thrown on failure.

Inherited from posix::basic_descriptor.

Cancel all asynchronous operations associated with the descriptor.

boost::system::error_code cancel(
    boost::system::error_code & ec);

This function causes all outstanding asynchronous read or write operations to finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error.

Parameters

ec

Set to indicate what error occurred, if any.

Close the descriptor.

void close();
  » more...

boost::system::error_code close(
    boost::system::error_code & ec);
  » more...

Inherited from posix::basic_descriptor.

Close the descriptor.

void close();

This function is used to close the descriptor. Any asynchronous read or write operations will be cancelled immediately, and will complete with the boost::asio::error::operation_aborted error.

Exceptions

boost::system::system_error

Thrown on failure. Note that, even if the function indicates an error, the underlying descriptor is closed.

Inherited from posix::basic_descriptor.

Close the descriptor.

boost::system::error_code close(
    boost::system::error_code & ec);

This function is used to close the descriptor. Any asynchronous read or write operations will be cancelled immediately, and will complete with the boost::asio::error::operation_aborted error.

Parameters

ec

Set to indicate what error occurred, if any. Note that, even if the function indicates an error, the underlying descriptor is closed.

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();
  » more...

const implementation_type & get_implementation() const;
  » more...

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

const implementation_type & get_implementation() const;

Inherited from basic_io_object.

Get the io_service associated with the object.

boost::asio::io_service & get_io_service();

This function may be used to obtain the io_service object that the I/O object uses to dispatch handlers for asynchronous operations.

Return Value

A reference to the io_service object that the I/O object will use to dispatch handlers. Ownership is not transferred to the caller.

Get the service associated with the I/O object.

service_type & get_service();
  » more...

const service_type & get_service() const;
  » more...

Inherited from basic_io_object.

Get the service associated with the I/O object.

service_type & get_service();

Inherited from basic_io_object.

Get the service associated with the I/O object.

const service_type & get_service() const;

Inherited from basic_io_object.

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

implementation_type implementation;

Inherited from basic_io_object.

The underlying implementation type of I/O object.

typedef service_type::implementation_type implementation_type;
Requirements

Header: boost/asio/posix/basic_stream_descriptor.hpp

Convenience header: boost/asio.hpp

Perform an IO control command on the descriptor.

void io_control(
    IoControlCommand & command);
  » more...

boost::system::error_code io_control(
    IoControlCommand & command,
    boost::system::error_code & ec);
  » more...

Inherited from posix::basic_descriptor.

Perform an IO control command on the descriptor.

template<
    typename IoControlCommand>
void io_control(
    IoControlCommand & command);

This function is used to execute an IO control command on the descriptor.

Parameters

command

The IO control command to be performed on the descriptor.

Exceptions

boost::system::system_error

Thrown on failure.

Example

Getting the number of bytes ready to read:

boost::asio::posix::stream_descriptor descriptor(io_service);
...
boost::asio::posix::stream_descriptor::bytes_readable command;
descriptor.io_control(command);
std::size_t bytes_readable = command.get();

Inherited from posix::basic_descriptor.

Perform an IO control command on the descriptor.

template<
    typename IoControlCommand>
boost::system::error_code io_control(
    IoControlCommand & command,
    boost::system::error_code & ec);

This function is used to execute an IO control command on the descriptor.

Parameters

command

The IO control command to be performed on the descriptor.

ec

Set to indicate what error occurred, if any.

Example

Getting the number of bytes ready to read:

boost::asio::posix::stream_descriptor descriptor(io_service);
...
boost::asio::posix::stream_descriptor::bytes_readable command;
boost::system::error_code ec;
descriptor.io_control(command, ec);
if (ec)
{
  // An error occurred.
}
std::size_t bytes_readable = command.get();

Inherited from posix::basic_descriptor.

Determine whether the descriptor is open.

bool is_open() const;

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();
  » more...

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;
  » more...

Inherited from posix::basic_descriptor.

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();

This function returns a reference to the lowest layer in a stack of layers. Since a posix::basic_descriptor cannot contain any further layers, it simply returns a reference to itself.

Return Value

A reference to the lowest layer in the stack of layers. Ownership is not transferred to the caller.

Inherited from posix::basic_descriptor.

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;

This function returns a const reference to the lowest layer in a stack of layers. Since a posix::basic_descriptor cannot contain any further layers, it simply returns a reference to itself.

Return Value

A const reference to the lowest layer in the stack of layers. Ownership is not transferred to the caller.

Inherited from posix::basic_descriptor.

A posix::basic_descriptor is always the lowest layer.

typedef basic_descriptor< StreamDescriptorService > lowest_layer_type;
Types

Name

Description

bytes_readable

IO control command to get the amount of data that can be read without blocking.

implementation_type

The underlying implementation type of I/O object.

lowest_layer_type

A basic_descriptor is always the lowest layer.

native_handle_type

The native representation of a descriptor.

native_type

(Deprecated: Use native_handle_type.) The native representation of a descriptor.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the descriptor.

service_type

The type of the service that will be used to provide I/O operations.

Member Functions

Name

Description

assign

Assign an existing native descriptor to the descriptor.

basic_descriptor

Construct a basic_descriptor without opening it.

Construct a basic_descriptor on an existing native descriptor.

Move-construct a basic_descriptor from another.

cancel

Cancel all asynchronous operations associated with the descriptor.

close

Close the descriptor.

get_io_service

Get the io_service associated with the object.

io_control

Perform an IO control command on the descriptor.

is_open

Determine whether the descriptor is open.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native descriptor representation.

native_handle

Get the native descriptor representation.

native_non_blocking

Gets the non-blocking mode of the native descriptor implementation.

Sets the non-blocking mode of the native descriptor implementation.

non_blocking

Gets the non-blocking mode of the descriptor.

Sets the non-blocking mode of the descriptor.

operator=

Move-assign a basic_descriptor from another.

release

Release ownership of the native descriptor implementation.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

~basic_descriptor

Protected destructor to prevent deletion through this type.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The posix::basic_descriptor class template provides the ability to wrap a POSIX descriptor.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/posix/basic_stream_descriptor.hpp

Convenience header: boost/asio.hpp

Inherited from posix::basic_descriptor.

(Deprecated: Use native_handle().) Get the native descriptor representation.

native_type native();

This function may be used to obtain the underlying representation of the descriptor. This is intended to allow access to native descriptor functionality that is not otherwise provided.

Inherited from posix::basic_descriptor.

Get the native descriptor representation.

native_handle_type native_handle();

This function may be used to obtain the underlying representation of the descriptor. This is intended to allow access to native descriptor functionality that is not otherwise provided.

The native representation of a descriptor.

typedef StreamDescriptorService::native_handle_type native_handle_type;
Requirements

Header: boost/asio/posix/basic_stream_descriptor.hpp

Convenience header: boost/asio.hpp

Gets the non-blocking mode of the native descriptor implementation.

bool native_non_blocking() const;
  » more...

Sets the non-blocking mode of the native descriptor implementation.

void native_non_blocking(
    bool mode);
  » more...

boost::system::error_code native_non_blocking(
    bool mode,
    boost::system::error_code & ec);
  » more...

Inherited from posix::basic_descriptor.

Gets the non-blocking mode of the native descriptor implementation.

bool native_non_blocking() const;

This function is used to retrieve the non-blocking mode of the underlying native descriptor. This mode has no effect on the behaviour of the descriptor object's synchronous operations.

Return Value

true if the underlying descriptor is in non-blocking mode and direct system calls may fail with boost::asio::error::would_block (or the equivalent system error).

Remarks

The current non-blocking mode is cached by the descriptor object. Consequently, the return value may be incorrect if the non-blocking mode was set directly on the native descriptor.

Inherited from posix::basic_descriptor.

Sets the non-blocking mode of the native descriptor implementation.

void native_non_blocking(
    bool mode);

This function is used to modify the non-blocking mode of the underlying native descriptor. It has no effect on the behaviour of the descriptor object's synchronous operations.

Parameters

mode

If true, the underlying descriptor is put into non-blocking mode and direct system calls may fail with boost::asio::error::would_block (or the equivalent system error).

Exceptions

boost::system::system_error

Thrown on failure. If the mode is false, but the current value of non_blocking() is true, this function fails with boost::asio::error::invalid_argument, as the combination does not make sense.

Inherited from posix::basic_descriptor.

Sets the non-blocking mode of the native descriptor implementation.

boost::system::error_code native_non_blocking(
    bool mode,
    boost::system::error_code & ec);

This function is used to modify the non-blocking mode of the underlying native descriptor. It has no effect on the behaviour of the descriptor object's synchronous operations.

Parameters

mode

If true, the underlying descriptor is put into non-blocking mode and direct system calls may fail with boost::asio::error::would_block (or the equivalent system error).

ec

Set to indicate what error occurred, if any. If the mode is false, but the current value of non_blocking() is true, this function fails with boost::asio::error::invalid_argument, as the combination does not make sense.

(Deprecated: Use native_handle_type.) The native representation of a descriptor.

typedef StreamDescriptorService::native_handle_type native_type;
Requirements

Header: boost/asio/posix/basic_stream_descriptor.hpp

Convenience header: boost/asio.hpp

Gets the non-blocking mode of the descriptor.

bool non_blocking() const;
  » more...

Sets the non-blocking mode of the descriptor.

void non_blocking(
    bool mode);
  » more...

boost::system::error_code non_blocking(
    bool mode,
    boost::system::error_code & ec);
  » more...

Inherited from posix::basic_descriptor.

Gets the non-blocking mode of the descriptor.

bool non_blocking() const;
Return Value

true if the descriptor's synchronous operations will fail with boost::asio::error::would_block if they are unable to perform the requested operation immediately. If false, synchronous operations will block until complete.

Remarks

The non-blocking mode has no effect on the behaviour of asynchronous operations. Asynchronous operations will never fail with the error boost::asio::error::would_block.

Inherited from posix::basic_descriptor.

Sets the non-blocking mode of the descriptor.

void non_blocking(
    bool mode);
Parameters

mode

If true, the descriptor's synchronous operations will fail with boost::asio::error::would_block if they are unable to perform the requested operation immediately. If false, synchronous operations will block until complete.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

The non-blocking mode has no effect on the behaviour of asynchronous operations. Asynchronous operations will never fail with the error boost::asio::error::would_block.

Inherited from posix::basic_descriptor.

Sets the non-blocking mode of the descriptor.

boost::system::error_code non_blocking(
    bool mode,
    boost::system::error_code & ec);
Parameters

mode

If true, the descriptor's synchronous operations will fail with boost::asio::error::would_block if they are unable to perform the requested operation immediately. If false, synchronous operations will block until complete.

ec

Set to indicate what error occurred, if any.

Remarks

The non-blocking mode has no effect on the behaviour of asynchronous operations. Asynchronous operations will never fail with the error boost::asio::error::would_block.

Inherited from posix::descriptor_base.

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the descriptor.

typedef implementation_defined non_blocking_io;

Implements the FIONBIO IO control command.

Example
boost::asio::posix::stream_descriptor descriptor(io_service);
...
boost::asio::descriptor_base::non_blocking_io command(true);
descriptor.io_control(command);
Requirements

Header: boost/asio/posix/basic_stream_descriptor.hpp

Convenience header: boost/asio.hpp

Move-assign a posix::basic_stream_descriptor from another.

basic_stream_descriptor & operator=(
    basic_stream_descriptor && other);

This assignment operator moves a stream descriptor from one object to another.

Parameters

other

The other posix::basic_stream_descriptor object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_stream_descriptor(io_service&) constructor.

Read some data from the descriptor.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers);
  » more...

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);
  » more...

Read some data from the descriptor.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers);

This function is used to read data from the stream descriptor. The function call will block until one or more bytes of data has been read successfully, or until an error occurs.

Parameters

buffers

One or more buffers into which the data will be read.

Return Value

The number of bytes read.

Exceptions

boost::system::system_error

Thrown on failure. An error code of boost::asio::error::eof indicates that the connection was closed by the peer.

Remarks

The read_some operation may not read all of the requested number of bytes. Consider using the read function if you need to ensure that the requested amount of data is read before the blocking operation completes.

Example

To read into a single data buffer use the buffer function as follows:

descriptor.read_some(boost::asio::buffer(data, size));

See the buffer documentation for information on reading into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Read some data from the descriptor.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);

This function is used to read data from the stream descriptor. The function call will block until one or more bytes of data has been read successfully, or until an error occurs.

Parameters

buffers

One or more buffers into which the data will be read.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes read. Returns 0 if an error occurred.

Remarks

The read_some operation may not read all of the requested number of bytes. Consider using the read function if you need to ensure that the requested amount of data is read before the blocking operation completes.

Inherited from posix::basic_descriptor.

Release ownership of the native descriptor implementation.

native_handle_type release();

This function may be used to obtain the underlying representation of the descriptor. After calling this function, is_open() returns false. The caller is responsible for closing the descriptor.

All outstanding asynchronous read or write operations will finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error.

Inherited from basic_io_object.

(Deprecated: Use get_service().) The service associated with the I/O object.

service_type & service;
Remarks

Available only for services that do not support movability.

Inherited from basic_io_object.

The type of the service that will be used to provide I/O operations.

typedef StreamDescriptorService service_type;
Requirements

Header: boost/asio/posix/basic_stream_descriptor.hpp

Convenience header: boost/asio.hpp

Write some data to the descriptor.

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers);
  » more...

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers,
    boost::system::error_code & ec);
  » more...

Write some data to the descriptor.

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers);

This function is used to write data to the stream descriptor. The function call will block until one or more bytes of the data has been written successfully, or until an error occurs.

Parameters

buffers

One or more data buffers to be written to the descriptor.

Return Value

The number of bytes written.

Exceptions

boost::system::system_error

Thrown on failure. An error code of boost::asio::error::eof indicates that the connection was closed by the peer.

Remarks

The write_some operation may not transmit all of the data to the peer. Consider using the write function if you need to ensure that all data is written before the blocking operation completes.

Example

To write a single data buffer use the buffer function as follows:

descriptor.write_some(boost::asio::buffer(data, size));

See the buffer documentation for information on writing multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Write some data to the descriptor.

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers,
    boost::system::error_code & ec);

This function is used to write data to the stream descriptor. The function call will block until one or more bytes of the data has been written successfully, or until an error occurs.

Parameters

buffers

One or more data buffers to be written to the descriptor.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes written. Returns 0 if an error occurred.

Remarks

The write_some operation may not transmit all of the data to the peer. Consider using the write function if you need to ensure that all data is written before the blocking operation completes.

The posix::descriptor_base class is used as a base for the posix::basic_stream_descriptor class template so that we have a common place to define the associated IO control commands.

class descriptor_base
Types

Name

Description

bytes_readable

IO control command to get the amount of data that can be read without blocking.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the descriptor.

Protected Member Functions

Name

Description

~descriptor_base

Protected destructor to prevent deletion through this type.

Requirements

Header: boost/asio/posix/descriptor_base.hpp

Convenience header: boost/asio.hpp

IO control command to get the amount of data that can be read without blocking.

typedef implementation_defined bytes_readable;

Implements the FIONREAD IO control command.

Example
boost::asio::posix::stream_descriptor descriptor(io_service);
...
boost::asio::descriptor_base::bytes_readable command(true);
descriptor.io_control(command);
std::size_t bytes_readable = command.get();
Requirements

Header: boost/asio/posix/descriptor_base.hpp

Convenience header: boost/asio.hpp

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the descriptor.

typedef implementation_defined non_blocking_io;

Implements the FIONBIO IO control command.

Example
boost::asio::posix::stream_descriptor descriptor(io_service);
...
boost::asio::descriptor_base::non_blocking_io command(true);
descriptor.io_control(command);
Requirements

Header: boost/asio/posix/descriptor_base.hpp

Convenience header: boost/asio.hpp

Protected destructor to prevent deletion through this type.

~descriptor_base();

Typedef for the typical usage of a stream-oriented descriptor.

typedef basic_stream_descriptor stream_descriptor;
Types

Name

Description

bytes_readable

IO control command to get the amount of data that can be read without blocking.

implementation_type

The underlying implementation type of I/O object.

lowest_layer_type

A basic_descriptor is always the lowest layer.

native_handle_type

The native representation of a descriptor.

native_type

(Deprecated: Use native_handle_type.) The native representation of a descriptor.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the descriptor.

service_type

The type of the service that will be used to provide I/O operations.

Member Functions

Name

Description

assign

Assign an existing native descriptor to the descriptor.

async_read_some

Start an asynchronous read.

async_write_some

Start an asynchronous write.

basic_stream_descriptor

Construct a basic_stream_descriptor without opening it.

Construct a basic_stream_descriptor on an existing native descriptor.

Move-construct a basic_stream_descriptor from another.

cancel

Cancel all asynchronous operations associated with the descriptor.

close

Close the descriptor.

get_io_service

Get the io_service associated with the object.

io_control

Perform an IO control command on the descriptor.

is_open

Determine whether the descriptor is open.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native descriptor representation.

native_handle

Get the native descriptor representation.

native_non_blocking

Gets the non-blocking mode of the native descriptor implementation.

Sets the non-blocking mode of the native descriptor implementation.

non_blocking

Gets the non-blocking mode of the descriptor.

Sets the non-blocking mode of the descriptor.

operator=

Move-assign a basic_stream_descriptor from another.

read_some

Read some data from the descriptor.

release

Release ownership of the native descriptor implementation.

write_some

Write some data to the descriptor.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The posix::basic_stream_descriptor class template provides asynchronous and blocking stream-oriented descriptor functionality.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/posix/stream_descriptor.hpp

Convenience header: boost/asio.hpp

Default service implementation for a stream descriptor.

class stream_descriptor_service :
  public io_service::service
Types

Name

Description

implementation_type

The type of a stream descriptor implementation.

native_handle_type

The native descriptor type.

native_type

(Deprecated: Use native_handle_type.) The native descriptor type.

Member Functions

Name

Description

assign

Assign an existing native descriptor to a stream descriptor.

async_read_some

Start an asynchronous read.

async_write_some

Start an asynchronous write.

cancel

Cancel all asynchronous operations associated with the descriptor.

close

Close a stream descriptor implementation.

construct

Construct a new stream descriptor implementation.

destroy

Destroy a stream descriptor implementation.

get_io_service

Get the io_service object that owns the service.

io_control

Perform an IO control command on the descriptor.

is_open

Determine whether the descriptor is open.

move_assign

Move-assign from another stream descriptor implementation.

move_construct

Move-construct a new stream descriptor implementation.

native

(Deprecated: Use native_handle().) Get the native descriptor implementation.

native_handle

Get the native descriptor implementation.

native_non_blocking

Gets the non-blocking mode of the native descriptor implementation.

Sets the non-blocking mode of the native descriptor implementation.

non_blocking

Gets the non-blocking mode of the descriptor.

Sets the non-blocking mode of the descriptor.

read_some

Read some data from the stream.

release

Release ownership of the native descriptor implementation.

stream_descriptor_service

Construct a new stream descriptor service for the specified io_service.

write_some

Write the given data to the stream.

Data Members

Name

Description

id

The unique service identifier.

Requirements

Header: boost/asio/posix/stream_descriptor_service.hpp

Convenience header: boost/asio.hpp

Assign an existing native descriptor to a stream descriptor.

boost::system::error_code assign(
    implementation_type & impl,
    const native_handle_type & native_descriptor,
    boost::system::error_code & ec);

Start an asynchronous read.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_read_some(
    implementation_type & impl,
    const MutableBufferSequence & buffers,
    ReadHandler handler);

Start an asynchronous write.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_write_some(
    implementation_type & impl,
    const ConstBufferSequence & buffers,
    WriteHandler handler);

Cancel all asynchronous operations associated with the descriptor.

boost::system::error_code cancel(
    implementation_type & impl,
    boost::system::error_code & ec);

Close a stream descriptor implementation.

boost::system::error_code close(
    implementation_type & impl,
    boost::system::error_code & ec);

Construct a new stream descriptor implementation.

void construct(
    implementation_type & impl);

Destroy a stream descriptor implementation.

void destroy(
    implementation_type & impl);

Inherited from io_service.

Get the io_service object that owns the service.

boost::asio::io_service & get_io_service();

The unique service identifier.

static boost::asio::io_service::id id;

The type of a stream descriptor implementation.

typedef implementation_defined implementation_type;
Requirements

Header: boost/asio/posix/stream_descriptor_service.hpp

Convenience header: boost/asio.hpp

Perform an IO control command on the descriptor.

template<
    typename IoControlCommand>
boost::system::error_code io_control(
    implementation_type & impl,
    IoControlCommand & command,
    boost::system::error_code & ec);

Determine whether the descriptor is open.

bool is_open(
    const implementation_type & impl) const;

Move-assign from another stream descriptor implementation.

void move_assign(
    implementation_type & impl,
    stream_descriptor_service & other_service,
    implementation_type & other_impl);

Move-construct a new stream descriptor implementation.

void move_construct(
    implementation_type & impl,
    implementation_type & other_impl);

(Deprecated: Use native_handle().) Get the native descriptor implementation.

native_type native(
    implementation_type & impl);

Get the native descriptor implementation.

native_handle_type native_handle(
    implementation_type & impl);

The native descriptor type.

typedef implementation_defined native_handle_type;
Requirements

Header: boost/asio/posix/stream_descriptor_service.hpp

Convenience header: boost/asio.hpp

Gets the non-blocking mode of the native descriptor implementation.

bool native_non_blocking(
    const implementation_type & impl) const;
  » more...

Sets the non-blocking mode of the native descriptor implementation.

boost::system::error_code native_non_blocking(
    implementation_type & impl,
    bool mode,
    boost::system::error_code & ec);
  » more...

Gets the non-blocking mode of the native descriptor implementation.

bool native_non_blocking(
    const implementation_type & impl) const;

Sets the non-blocking mode of the native descriptor implementation.

boost::system::error_code native_non_blocking(
    implementation_type & impl,
    bool mode,
    boost::system::error_code & ec);

(Deprecated: Use native_handle_type.) The native descriptor type.

typedef implementation_defined native_type;
Requirements

Header: boost/asio/posix/stream_descriptor_service.hpp

Convenience header: boost/asio.hpp

Gets the non-blocking mode of the descriptor.

bool non_blocking(
    const implementation_type & impl) const;
  » more...

Sets the non-blocking mode of the descriptor.

boost::system::error_code non_blocking(
    implementation_type & impl,
    bool mode,
    boost::system::error_code & ec);
  » more...

Gets the non-blocking mode of the descriptor.

bool non_blocking(
    const implementation_type & impl) const;

Sets the non-blocking mode of the descriptor.

boost::system::error_code non_blocking(
    implementation_type & impl,
    bool mode,
    boost::system::error_code & ec);

Read some data from the stream.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    implementation_type & impl,
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);

Release ownership of the native descriptor implementation.

native_handle_type release(
    implementation_type & impl);

Construct a new stream descriptor service for the specified io_service.

stream_descriptor_service(
    boost::asio::io_service & io_service);

Write the given data to the stream.

template<
    typename ConstBufferSequence>
std::size_t write_some(
    implementation_type & impl,
    const ConstBufferSequence & buffers,
    boost::system::error_code & ec);

Default service implementation for a raw socket.

template<
    typename Protocol>
class raw_socket_service :
  public io_service::service
Types

Name

Description

endpoint_type

The endpoint type.

implementation_type

The type of a raw socket.

native_handle_type

The native socket type.

native_type

(Deprecated: Use native_handle_type.) The native socket type.

protocol_type

The protocol type.

Member Functions

Name

Description

assign

Assign an existing native socket to a raw socket.

async_connect

Start an asynchronous connect.

async_receive

Start an asynchronous receive.

async_receive_from

Start an asynchronous receive that will get the endpoint of the sender.

async_send

Start an asynchronous send.

async_send_to

Start an asynchronous send.

at_mark

Determine whether the socket is at the out-of-band data mark.

available

Determine the number of bytes available for reading.

bind

cancel

Cancel all asynchronous operations associated with the socket.

close

Close a raw socket implementation.

connect

Connect the raw socket to the specified endpoint.

construct

Construct a new raw socket implementation.

converting_move_construct

Move-construct a new raw socket implementation from another protocol type.

destroy

Destroy a raw socket implementation.

get_io_service

Get the io_service object that owns the service.

get_option

Get a socket option.

io_control

Perform an IO control command on the socket.

is_open

Determine whether the socket is open.

local_endpoint

Get the local endpoint.

move_assign

Move-assign from another raw socket implementation.

move_construct

Move-construct a new raw socket implementation.

native

(Deprecated: Use native_handle().) Get the native socket implementation.

native_handle

Get the native socket implementation.

native_non_blocking

Gets the non-blocking mode of the native socket implementation.

Sets the non-blocking mode of the native socket implementation.

non_blocking

Gets the non-blocking mode of the socket.

Sets the non-blocking mode of the socket.

open

raw_socket_service

Construct a new raw socket service for the specified io_service.

receive

Receive some data from the peer.

receive_from

Receive raw data with the endpoint of the sender.

remote_endpoint

Get the remote endpoint.

send

Send the given data to the peer.

send_to

Send raw data to the specified endpoint.

set_option

Set a socket option.

shutdown

Disable sends or receives on the socket.

Data Members

Name

Description

id

The unique service identifier.

Requirements

Header: boost/asio/raw_socket_service.hpp

Convenience header: boost/asio.hpp

Assign an existing native socket to a raw socket.

boost::system::error_code assign(
    implementation_type & impl,
    const protocol_type & protocol,
    const native_handle_type & native_socket,
    boost::system::error_code & ec);

Start an asynchronous connect.

template<
    typename ConnectHandler>
void-or-deduced async_connect(
    implementation_type & impl,
    const endpoint_type & peer_endpoint,
    ConnectHandler handler);

Start an asynchronous receive.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_receive(
    implementation_type & impl,
    const MutableBufferSequence & buffers,
    socket_base::message_flags flags,
    ReadHandler handler);

Start an asynchronous receive that will get the endpoint of the sender.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_receive_from(
    implementation_type & impl,
    const MutableBufferSequence & buffers,
    endpoint_type & sender_endpoint,
    socket_base::message_flags flags,
    ReadHandler handler);

Start an asynchronous send.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_send(
    implementation_type & impl,
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags,
    WriteHandler handler);

Start an asynchronous send.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_send_to(
    implementation_type & impl,
    const ConstBufferSequence & buffers,
    const endpoint_type & destination,
    socket_base::message_flags flags,
    WriteHandler handler);

Determine whether the socket is at the out-of-band data mark.

bool at_mark(
    const implementation_type & impl,
    boost::system::error_code & ec) const;

Determine the number of bytes available for reading.

std::size_t available(
    const implementation_type & impl,
    boost::system::error_code & ec) const;

boost::system::error_code bind(
    implementation_type & impl,
    const endpoint_type & endpoint,
    boost::system::error_code & ec);

Cancel all asynchronous operations associated with the socket.

boost::system::error_code cancel(
    implementation_type & impl,
    boost::system::error_code & ec);

Close a raw socket implementation.

boost::system::error_code close(
    implementation_type & impl,
    boost::system::error_code & ec);

Connect the raw socket to the specified endpoint.

boost::system::error_code connect(
    implementation_type & impl,
    const endpoint_type & peer_endpoint,
    boost::system::error_code & ec);

Construct a new raw socket implementation.

void construct(
    implementation_type & impl);

Move-construct a new raw socket implementation from another protocol type.

template<
    typename Protocol1>
void converting_move_construct(
    implementation_type & impl,
    typename raw_socket_service< Protocol1 >::implementation_type & other_impl,
    typename enable_if< is_convertible< Protocol1, Protocol >::value >::type *  = 0);

Destroy a raw socket implementation.

void destroy(
    implementation_type & impl);

The endpoint type.

typedef Protocol::endpoint endpoint_type;
Requirements

Header: boost/asio/raw_socket_service.hpp

Convenience header: boost/asio.hpp

Inherited from io_service.

Get the io_service object that owns the service.

boost::asio::io_service & get_io_service();

Get a socket option.

template<
    typename GettableSocketOption>
boost::system::error_code get_option(
    const implementation_type & impl,
    GettableSocketOption & option,
    boost::system::error_code & ec) const;

The unique service identifier.

static boost::asio::io_service::id id;

The type of a raw socket.

typedef implementation_defined implementation_type;
Requirements

Header: boost/asio/raw_socket_service.hpp

Convenience header: boost/asio.hpp

Perform an IO control command on the socket.

template<
    typename IoControlCommand>
boost::system::error_code io_control(
    implementation_type & impl,
    IoControlCommand & command,
    boost::system::error_code & ec);

Determine whether the socket is open.

bool is_open(
    const implementation_type & impl) const;

Get the local endpoint.

endpoint_type local_endpoint(
    const implementation_type & impl,
    boost::system::error_code & ec) const;

Move-assign from another raw socket implementation.

void move_assign(
    implementation_type & impl,
    raw_socket_service & other_service,
    implementation_type & other_impl);

Move-construct a new raw socket implementation.

void move_construct(
    implementation_type & impl,
    implementation_type & other_impl);

(Deprecated: Use native_handle().) Get the native socket implementation.

native_type native(
    implementation_type & impl);

Get the native socket implementation.

native_handle_type native_handle(
    implementation_type & impl);

The native socket type.

typedef implementation_defined native_handle_type;
Requirements

Header: boost/asio/raw_socket_service.hpp

Convenience header: boost/asio.hpp

Gets the non-blocking mode of the native socket implementation.

bool native_non_blocking(
    const implementation_type & impl) const;
  » more...

Sets the non-blocking mode of the native socket implementation.

boost::system::error_code native_non_blocking(
    implementation_type & impl,
    bool mode,
    boost::system::error_code & ec);
  » more...

Gets the non-blocking mode of the native socket implementation.

bool native_non_blocking(
    const implementation_type & impl) const;

Sets the non-blocking mode of the native socket implementation.

boost::system::error_code native_non_blocking(
    implementation_type & impl,
    bool mode,
    boost::system::error_code & ec);

(Deprecated: Use native_handle_type.) The native socket type.

typedef implementation_defined native_type;
Requirements

Header: boost/asio/raw_socket_service.hpp

Convenience header: boost/asio.hpp

Gets the non-blocking mode of the socket.

bool non_blocking(
    const implementation_type & impl) const;
  » more...

Sets the non-blocking mode of the socket.

boost::system::error_code non_blocking(
    implementation_type & impl,
    bool mode,
    boost::system::error_code & ec);
  » more...

Gets the non-blocking mode of the socket.

bool non_blocking(
    const implementation_type & impl) const;

Sets the non-blocking mode of the socket.

boost::system::error_code non_blocking(
    implementation_type & impl,
    bool mode,
    boost::system::error_code & ec);

boost::system::error_code open(
    implementation_type & impl,
    const protocol_type & protocol,
    boost::system::error_code & ec);

The protocol type.

typedef Protocol protocol_type;
Requirements

Header: boost/asio/raw_socket_service.hpp

Convenience header: boost/asio.hpp

Construct a new raw socket service for the specified io_service.

raw_socket_service(
    boost::asio::io_service & io_service);

Receive some data from the peer.

template<
    typename MutableBufferSequence>
std::size_t receive(
    implementation_type & impl,
    const MutableBufferSequence & buffers,
    socket_base::message_flags flags,
    boost::system::error_code & ec);

Receive raw data with the endpoint of the sender.

template<
    typename MutableBufferSequence>
std::size_t receive_from(
    implementation_type & impl,
    const MutableBufferSequence & buffers,
    endpoint_type & sender_endpoint,
    socket_base::message_flags flags,
    boost::system::error_code & ec);

Get the remote endpoint.

endpoint_type remote_endpoint(
    const implementation_type & impl,
    boost::system::error_code & ec) const;

Send the given data to the peer.

template<
    typename ConstBufferSequence>
std::size_t send(
    implementation_type & impl,
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags,
    boost::system::error_code & ec);

Send raw data to the specified endpoint.

template<
    typename ConstBufferSequence>
std::size_t send_to(
    implementation_type & impl,
    const ConstBufferSequence & buffers,
    const endpoint_type & destination,
    socket_base::message_flags flags,
    boost::system::error_code & ec);

Set a socket option.

template<
    typename SettableSocketOption>
boost::system::error_code set_option(
    implementation_type & impl,
    const SettableSocketOption & option,
    boost::system::error_code & ec);

Disable sends or receives on the socket.

boost::system::error_code shutdown(
    implementation_type & impl,
    socket_base::shutdown_type what,
    boost::system::error_code & ec);

Attempt to read a certain amount of data from a stream before returning.

template<
    typename SyncReadStream,
    typename MutableBufferSequence>
std::size_t read(
    SyncReadStream & s,
    const MutableBufferSequence & buffers);
  » more...

template<
    typename SyncReadStream,
    typename MutableBufferSequence>
std::size_t read(
    SyncReadStream & s,
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);
  » more...

template<
    typename SyncReadStream,
    typename MutableBufferSequence,
    typename CompletionCondition>
std::size_t read(
    SyncReadStream & s,
    const MutableBufferSequence & buffers,
    CompletionCondition completion_condition);
  » more...

template<
    typename SyncReadStream,
    typename MutableBufferSequence,
    typename CompletionCondition>
std::size_t read(
    SyncReadStream & s,
    const MutableBufferSequence & buffers,
    CompletionCondition completion_condition,
    boost::system::error_code & ec);
  » more...

template<
    typename SyncReadStream,
    typename Allocator>
std::size_t read(
    SyncReadStream & s,
    basic_streambuf< Allocator > & b);
  » more...

template<
    typename SyncReadStream,
    typename Allocator>
std::size_t read(
    SyncReadStream & s,
    basic_streambuf< Allocator > & b,
    boost::system::error_code & ec);
  » more...

template<
    typename SyncReadStream,
    typename Allocator,
    typename CompletionCondition>
std::size_t read(
    SyncReadStream & s,
    basic_streambuf< Allocator > & b,
    CompletionCondition completion_condition);
  » more...

template<
    typename SyncReadStream,
    typename Allocator,
    typename CompletionCondition>
std::size_t read(
    SyncReadStream & s,
    basic_streambuf< Allocator > & b,
    CompletionCondition completion_condition,
    boost::system::error_code & ec);
  » more...
Requirements

Header: boost/asio/read.hpp

Convenience header: boost/asio.hpp

Attempt to read a certain amount of data from a stream before returning.

template<
    typename SyncReadStream,
    typename MutableBufferSequence>
std::size_t read(
    SyncReadStream & s,
    const MutableBufferSequence & buffers);

This function is used to read a certain number of bytes of data from a stream. The call will block until one of the following conditions is true:

  • The supplied buffers are full. That is, the bytes transferred is equal to the sum of the buffer sizes.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the stream's read_some function.

Parameters

s

The stream from which the data is to be read. The type must support the SyncReadStream concept.

buffers

One or more buffers into which the data will be read. The sum of the buffer sizes indicates the maximum number of bytes to read from the stream.

Return Value

The number of bytes transferred.

Exceptions

boost::system::system_error

Thrown on failure.

Example

To read into a single data buffer use the buffer function as follows:

boost::asio::read(s, boost::asio::buffer(data, size));

See the buffer documentation for information on reading into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Remarks

This overload is equivalent to calling:

boost::asio::read(
    s, buffers,
    boost::asio::transfer_all());

Attempt to read a certain amount of data from a stream before returning.

template<
    typename SyncReadStream,
    typename MutableBufferSequence>
std::size_t read(
    SyncReadStream & s,
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);

This function is used to read a certain number of bytes of data from a stream. The call will block until one of the following conditions is true:

  • The supplied buffers are full. That is, the bytes transferred is equal to the sum of the buffer sizes.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the stream's read_some function.

Parameters

s

The stream from which the data is to be read. The type must support the SyncReadStream concept.

buffers

One or more buffers into which the data will be read. The sum of the buffer sizes indicates the maximum number of bytes to read from the stream.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes transferred.

Example

To read into a single data buffer use the buffer function as follows:

boost::asio::read(s, boost::asio::buffer(data, size), ec);

See the buffer documentation for information on reading into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Remarks

This overload is equivalent to calling:

boost::asio::read(
    s, buffers,
    boost::asio::transfer_all(), ec);

Attempt to read a certain amount of data from a stream before returning.

template<
    typename SyncReadStream,
    typename MutableBufferSequence,
    typename CompletionCondition>
std::size_t read(
    SyncReadStream & s,
    const MutableBufferSequence & buffers,
    CompletionCondition completion_condition);

This function is used to read a certain number of bytes of data from a stream. The call will block until one of the following conditions is true:

  • The supplied buffers are full. That is, the bytes transferred is equal to the sum of the buffer sizes.
  • The completion_condition function object returns 0.

This operation is implemented in terms of zero or more calls to the stream's read_some function.

Parameters

s

The stream from which the data is to be read. The type must support the SyncReadStream concept.

buffers

One or more buffers into which the data will be read. The sum of the buffer sizes indicates the maximum number of bytes to read from the stream.

completion_condition

The function object to be called to determine whether the read operation is complete. The signature of the function object must be:

std::size_t completion_condition(
  // Result of latest read_some operation.
  const boost::system::error_code& error,

  // Number of bytes transferred so far.
  std::size_t bytes_transferred
);

A return value of 0 indicates that the read operation is complete. A non-zero return value indicates the maximum number of bytes to be read on the next call to the stream's read_some function.

Return Value

The number of bytes transferred.

Exceptions

boost::system::system_error

Thrown on failure.

Example

To read into a single data buffer use the buffer function as follows:

boost::asio::read(s, boost::asio::buffer(data, size),
    boost::asio::transfer_at_least(32));

See the buffer documentation for information on reading into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Attempt to read a certain amount of data from a stream before returning.

template<
    typename SyncReadStream,
    typename MutableBufferSequence,
    typename CompletionCondition>
std::size_t read(
    SyncReadStream & s,
    const MutableBufferSequence & buffers,
    CompletionCondition completion_condition,
    boost::system::error_code & ec);

This function is used to read a certain number of bytes of data from a stream. The call will block until one of the following conditions is true:

  • The supplied buffers are full. That is, the bytes transferred is equal to the sum of the buffer sizes.
  • The completion_condition function object returns 0.

This operation is implemented in terms of zero or more calls to the stream's read_some function.

Parameters

s

The stream from which the data is to be read. The type must support the SyncReadStream concept.

buffers

One or more buffers into which the data will be read. The sum of the buffer sizes indicates the maximum number of bytes to read from the stream.

completion_condition

The function object to be called to determine whether the read operation is complete. The signature of the function object must be:

std::size_t completion_condition(
  // Result of latest read_some operation.
  const boost::system::error_code& error,

  // Number of bytes transferred so far.
  std::size_t bytes_transferred
);

A return value of 0 indicates that the read operation is complete. A non-zero return value indicates the maximum number of bytes to be read on the next call to the stream's read_some function.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes read. If an error occurs, returns the total number of bytes successfully transferred prior to the error.

Attempt to read a certain amount of data from a stream before returning.

template<
    typename SyncReadStream,
    typename Allocator>
std::size_t read(
    SyncReadStream & s,
    basic_streambuf< Allocator > & b);

This function is used to read a certain number of bytes of data from a stream. The call will block until one of the following conditions is true:

  • The supplied buffer is full (that is, it has reached maximum size).
  • An error occurred.

This operation is implemented in terms of zero or more calls to the stream's read_some function.

Parameters

s

The stream from which the data is to be read. The type must support the SyncReadStream concept.

b

The basic_streambuf object into which the data will be read.

Return Value

The number of bytes transferred.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

This overload is equivalent to calling:

boost::asio::read(
    s, b,
    boost::asio::transfer_all());

Attempt to read a certain amount of data from a stream before returning.

template<
    typename SyncReadStream,
    typename Allocator>
std::size_t read(
    SyncReadStream & s,
    basic_streambuf< Allocator > & b,
    boost::system::error_code & ec);

This function is used to read a certain number of bytes of data from a stream. The call will block until one of the following conditions is true:

  • The supplied buffer is full (that is, it has reached maximum size).
  • An error occurred.

This operation is implemented in terms of zero or more calls to the stream's read_some function.

Parameters

s

The stream from which the data is to be read. The type must support the SyncReadStream concept.

b

The basic_streambuf object into which the data will be read.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes transferred.

Remarks

This overload is equivalent to calling:

boost::asio::read(
    s, b,
    boost::asio::transfer_all(), ec);

Attempt to read a certain amount of data from a stream before returning.

template<
    typename SyncReadStream,
    typename Allocator,
    typename CompletionCondition>
std::size_t read(
    SyncReadStream & s,
    basic_streambuf< Allocator > & b,
    CompletionCondition completion_condition);

This function is used to read a certain number of bytes of data from a stream. The call will block until one of the following conditions is true:

  • The supplied buffer is full (that is, it has reached maximum size).
  • The completion_condition function object returns 0.

This operation is implemented in terms of zero or more calls to the stream's read_some function.

Parameters

s

The stream from which the data is to be read. The type must support the SyncReadStream concept.

b

The basic_streambuf object into which the data will be read.

completion_condition

The function object to be called to determine whether the read operation is complete. The signature of the function object must be:

std::size_t completion_condition(
  // Result of latest read_some operation.
  const boost::system::error_code& error,

  // Number of bytes transferred so far.
  std::size_t bytes_transferred
);

A return value of 0 indicates that the read operation is complete. A non-zero return value indicates the maximum number of bytes to be read on the next call to the stream's read_some function.

Return Value

The number of bytes transferred.

Exceptions

boost::system::system_error

Thrown on failure.

Attempt to read a certain amount of data from a stream before returning.

template<
    typename SyncReadStream,
    typename Allocator,
    typename CompletionCondition>
std::size_t read(
    SyncReadStream & s,
    basic_streambuf< Allocator > & b,
    CompletionCondition completion_condition,
    boost::system::error_code & ec);

This function is used to read a certain number of bytes of data from a stream. The call will block until one of the following conditions is true:

  • The supplied buffer is full (that is, it has reached maximum size).
  • The completion_condition function object returns 0.

This operation is implemented in terms of zero or more calls to the stream's read_some function.

Parameters

s

The stream from which the data is to be read. The type must support the SyncReadStream concept.

b

The basic_streambuf object into which the data will be read.

completion_condition

The function object to be called to determine whether the read operation is complete. The signature of the function object must be:

std::size_t completion_condition(
  // Result of latest read_some operation.
  const boost::system::error_code& error,

  // Number of bytes transferred so far.
  std::size_t bytes_transferred
);

A return value of 0 indicates that the read operation is complete. A non-zero return value indicates the maximum number of bytes to be read on the next call to the stream's read_some function.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes read. If an error occurs, returns the total number of bytes successfully transferred prior to the error.

Attempt to read a certain amount of data at the specified offset before returning.

template<
    typename SyncRandomAccessReadDevice,
    typename MutableBufferSequence>
std::size_t read_at(
    SyncRandomAccessReadDevice & d,
    uint64_t offset,
    const MutableBufferSequence & buffers);
  » more...

template<
    typename SyncRandomAccessReadDevice,
    typename MutableBufferSequence>
std::size_t read_at(
    SyncRandomAccessReadDevice & d,
    uint64_t offset,
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);
  » more...

template<
    typename SyncRandomAccessReadDevice,
    typename MutableBufferSequence,
    typename CompletionCondition>
std::size_t read_at(
    SyncRandomAccessReadDevice & d,
    uint64_t offset,
    const MutableBufferSequence & buffers,
    CompletionCondition completion_condition);
  » more...

template<
    typename SyncRandomAccessReadDevice,
    typename MutableBufferSequence,
    typename CompletionCondition>
std::size_t read_at(
    SyncRandomAccessReadDevice & d,
    uint64_t offset,
    const MutableBufferSequence & buffers,
    CompletionCondition completion_condition,
    boost::system::error_code & ec);
  » more...

template<
    typename SyncRandomAccessReadDevice,
    typename Allocator>
std::size_t read_at(
    SyncRandomAccessReadDevice & d,
    uint64_t offset,
    basic_streambuf< Allocator > & b);
  » more...

template<
    typename SyncRandomAccessReadDevice,
    typename Allocator>
std::size_t read_at(
    SyncRandomAccessReadDevice & d,
    uint64_t offset,
    basic_streambuf< Allocator > & b,
    boost::system::error_code & ec);
  » more...

template<
    typename SyncRandomAccessReadDevice,
    typename Allocator,
    typename CompletionCondition>
std::size_t read_at(
    SyncRandomAccessReadDevice & d,
    uint64_t offset,
    basic_streambuf< Allocator > & b,
    CompletionCondition completion_condition);
  » more...

template<
    typename SyncRandomAccessReadDevice,
    typename Allocator,
    typename CompletionCondition>
std::size_t read_at(
    SyncRandomAccessReadDevice & d,
    uint64_t offset,
    basic_streambuf< Allocator > & b,
    CompletionCondition completion_condition,
    boost::system::error_code & ec);
  » more...
Requirements

Header: boost/asio/read_at.hpp

Convenience header: boost/asio.hpp

Attempt to read a certain amount of data at the specified offset before returning.

template<
    typename SyncRandomAccessReadDevice,
    typename MutableBufferSequence>
std::size_t read_at(
    SyncRandomAccessReadDevice & d,
    uint64_t offset,
    const MutableBufferSequence & buffers);

This function is used to read a certain number of bytes of data from a random access device at the specified offset. The call will block until one of the following conditions is true:

  • The supplied buffers are full. That is, the bytes transferred is equal to the sum of the buffer sizes.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the device's read_some_at function.

Parameters

d

The device from which the data is to be read. The type must support the SyncRandomAccessReadDevice concept.

offset

The offset at which the data will be read.

buffers

One or more buffers into which the data will be read. The sum of the buffer sizes indicates the maximum number of bytes to read from the device.

Return Value

The number of bytes transferred.

Exceptions

boost::system::system_error

Thrown on failure.

Example

To read into a single data buffer use the buffer function as follows:

boost::asio::read_at(d, 42, boost::asio::buffer(data, size));

See the buffer documentation for information on reading into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Remarks

This overload is equivalent to calling:

boost::asio::read_at(
    d, 42, buffers,
    boost::asio::transfer_all());

Attempt to read a certain amount of data at the specified offset before returning.

template<
    typename SyncRandomAccessReadDevice,
    typename MutableBufferSequence>
std::size_t read_at(
    SyncRandomAccessReadDevice & d,
    uint64_t offset,
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);

This function is used to read a certain number of bytes of data from a random access device at the specified offset. The call will block until one of the following conditions is true:

  • The supplied buffers are full. That is, the bytes transferred is equal to the sum of the buffer sizes.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the device's read_some_at function.

Parameters

d

The device from which the data is to be read. The type must support the SyncRandomAccessReadDevice concept.

offset

The offset at which the data will be read.

buffers

One or more buffers into which the data will be read. The sum of the buffer sizes indicates the maximum number of bytes to read from the device.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes transferred.

Example

To read into a single data buffer use the buffer function as follows:

boost::asio::read_at(d, 42,
    boost::asio::buffer(data, size), ec);

See the buffer documentation for information on reading into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Remarks

This overload is equivalent to calling:

boost::asio::read_at(
    d, 42, buffers,
    boost::asio::transfer_all(), ec);

Attempt to read a certain amount of data at the specified offset before returning.

template<
    typename SyncRandomAccessReadDevice,
    typename MutableBufferSequence,
    typename CompletionCondition>
std::size_t read_at(
    SyncRandomAccessReadDevice & d,
    uint64_t offset,
    const MutableBufferSequence & buffers,
    CompletionCondition completion_condition);

This function is used to read a certain number of bytes of data from a random access device at the specified offset. The call will block until one of the following conditions is true:

  • The supplied buffers are full. That is, the bytes transferred is equal to the sum of the buffer sizes.
  • The completion_condition function object returns 0.

This operation is implemented in terms of zero or more calls to the device's read_some_at function.

Parameters

d

The device from which the data is to be read. The type must support the SyncRandomAccessReadDevice concept.

offset

The offset at which the data will be read.

buffers

One or more buffers into which the data will be read. The sum of the buffer sizes indicates the maximum number of bytes to read from the device.

completion_condition

The function object to be called to determine whether the read operation is complete. The signature of the function object must be:

std::size_t completion_condition(
  // Result of latest read_some_at operation.
  const boost::system::error_code& error,

  // Number of bytes transferred so far.
  std::size_t bytes_transferred
);

A return value of 0 indicates that the read operation is complete. A non-zero return value indicates the maximum number of bytes to be read on the next call to the device's read_some_at function.

Return Value

The number of bytes transferred.

Exceptions

boost::system::system_error

Thrown on failure.

Example

To read into a single data buffer use the buffer function as follows:

boost::asio::read_at(d, 42, boost::asio::buffer(data, size),
    boost::asio::transfer_at_least(32));

See the buffer documentation for information on reading into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Attempt to read a certain amount of data at the specified offset before returning.

template<
    typename SyncRandomAccessReadDevice,
    typename MutableBufferSequence,
    typename CompletionCondition>
std::size_t read_at(
    SyncRandomAccessReadDevice & d,
    uint64_t offset,
    const MutableBufferSequence & buffers,
    CompletionCondition completion_condition,
    boost::system::error_code & ec);

This function is used to read a certain number of bytes of data from a random access device at the specified offset. The call will block until one of the following conditions is true:

  • The supplied buffers are full. That is, the bytes transferred is equal to the sum of the buffer sizes.
  • The completion_condition function object returns 0.

This operation is implemented in terms of zero or more calls to the device's read_some_at function.

Parameters

d

The device from which the data is to be read. The type must support the SyncRandomAccessReadDevice concept.

offset

The offset at which the data will be read.

buffers

One or more buffers into which the data will be read. The sum of the buffer sizes indicates the maximum number of bytes to read from the device.

completion_condition

The function object to be called to determine whether the read operation is complete. The signature of the function object must be:

std::size_t completion_condition(
  // Result of latest read_some_at operation.
  const boost::system::error_code& error,

  // Number of bytes transferred so far.
  std::size_t bytes_transferred
);

A return value of 0 indicates that the read operation is complete. A non-zero return value indicates the maximum number of bytes to be read on the next call to the device's read_some_at function.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes read. If an error occurs, returns the total number of bytes successfully transferred prior to the error.

Attempt to read a certain amount of data at the specified offset before returning.

template<
    typename SyncRandomAccessReadDevice,
    typename Allocator>
std::size_t read_at(
    SyncRandomAccessReadDevice & d,
    uint64_t offset,
    basic_streambuf< Allocator > & b);

This function is used to read a certain number of bytes of data from a random access device at the specified offset. The call will block until one of the following conditions is true:

  • An error occurred.

This operation is implemented in terms of zero or more calls to the device's read_some_at function.

Parameters

d

The device from which the data is to be read. The type must support the SyncRandomAccessReadDevice concept.

offset

The offset at which the data will be read.

b

The basic_streambuf object into which the data will be read.

Return Value

The number of bytes transferred.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

This overload is equivalent to calling:

boost::asio::read_at(
    d, 42, b,
    boost::asio::transfer_all());

Attempt to read a certain amount of data at the specified offset before returning.

template<
    typename SyncRandomAccessReadDevice,
    typename Allocator>
std::size_t read_at(
    SyncRandomAccessReadDevice & d,
    uint64_t offset,
    basic_streambuf< Allocator > & b,
    boost::system::error_code & ec);

This function is used to read a certain number of bytes of data from a random access device at the specified offset. The call will block until one of the following conditions is true:

  • An error occurred.

This operation is implemented in terms of zero or more calls to the device's read_some_at function.

Parameters

d

The device from which the data is to be read. The type must support the SyncRandomAccessReadDevice concept.

offset

The offset at which the data will be read.

b

The basic_streambuf object into which the data will be read.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes transferred.

Remarks

This overload is equivalent to calling:

boost::asio::read_at(
    d, 42, b,
    boost::asio::transfer_all(), ec);

Attempt to read a certain amount of data at the specified offset before returning.

template<
    typename SyncRandomAccessReadDevice,
    typename Allocator,
    typename CompletionCondition>
std::size_t read_at(
    SyncRandomAccessReadDevice & d,
    uint64_t offset,
    basic_streambuf< Allocator > & b,
    CompletionCondition completion_condition);

This function is used to read a certain number of bytes of data from a random access device at the specified offset. The call will block until one of the following conditions is true:

  • The completion_condition function object returns 0.

This operation is implemented in terms of zero or more calls to the device's read_some_at function.

Parameters

d

The device from which the data is to be read. The type must support the SyncRandomAccessReadDevice concept.

offset

The offset at which the data will be read.

b

The basic_streambuf object into which the data will be read.

completion_condition

The function object to be called to determine whether the read operation is complete. The signature of the function object must be:

std::size_t completion_condition(
  // Result of latest read_some_at operation.
  const boost::system::error_code& error,

  // Number of bytes transferred so far.
  std::size_t bytes_transferred
);

A return value of 0 indicates that the read operation is complete. A non-zero return value indicates the maximum number of bytes to be read on the next call to the device's read_some_at function.

Return Value

The number of bytes transferred.

Exceptions

boost::system::system_error

Thrown on failure.

Attempt to read a certain amount of data at the specified offset before returning.

template<
    typename SyncRandomAccessReadDevice,
    typename Allocator,
    typename CompletionCondition>
std::size_t read_at(
    SyncRandomAccessReadDevice & d,
    uint64_t offset,
    basic_streambuf< Allocator > & b,
    CompletionCondition completion_condition,
    boost::system::error_code & ec);

This function is used to read a certain number of bytes of data from a random access device at the specified offset. The call will block until one of the following conditions is true:

  • The completion_condition function object returns 0.

This operation is implemented in terms of zero or more calls to the device's read_some_at function.

Parameters

d

The device from which the data is to be read. The type must support the SyncRandomAccessReadDevice concept.

offset

The offset at which the data will be read.

b

The basic_streambuf object into which the data will be read.

completion_condition

The function object to be called to determine whether the read operation is complete. The signature of the function object must be:

std::size_t completion_condition(
  // Result of latest read_some_at operation.
  const boost::system::error_code& error,

  // Number of bytes transferred so far.
  std::size_t bytes_transferred
);

A return value of 0 indicates that the read operation is complete. A non-zero return value indicates the maximum number of bytes to be read on the next call to the device's read_some_at function.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes read. If an error occurs, returns the total number of bytes successfully transferred prior to the error.

Read data into a streambuf until it contains a delimiter, matches a regular expression, or a function object indicates a match.

template<
    typename SyncReadStream,
    typename Allocator>
std::size_t read_until(
    SyncReadStream & s,
    boost::asio::basic_streambuf< Allocator > & b,
    char delim);
  » more...

template<
    typename SyncReadStream,
    typename Allocator>
std::size_t read_until(
    SyncReadStream & s,
    boost::asio::basic_streambuf< Allocator > & b,
    char delim,
    boost::system::error_code & ec);
  » more...

template<
    typename SyncReadStream,
    typename Allocator>
std::size_t read_until(
    SyncReadStream & s,
    boost::asio::basic_streambuf< Allocator > & b,
    const std::string & delim);
  » more...

template<
    typename SyncReadStream,
    typename Allocator>
std::size_t read_until(
    SyncReadStream & s,
    boost::asio::basic_streambuf< Allocator > & b,
    const std::string & delim,
    boost::system::error_code & ec);
  » more...

template<
    typename SyncReadStream,
    typename Allocator>
std::size_t read_until(
    SyncReadStream & s,
    boost::asio::basic_streambuf< Allocator > & b,
    const boost::regex & expr);
  » more...

template<
    typename SyncReadStream,
    typename Allocator>
std::size_t read_until(
    SyncReadStream & s,
    boost::asio::basic_streambuf< Allocator > & b,
    const boost::regex & expr,
    boost::system::error_code & ec);
  » more...

template<
    typename SyncReadStream,
    typename Allocator,
    typename MatchCondition>
std::size_t read_until(
    SyncReadStream & s,
    boost::asio::basic_streambuf< Allocator > & b,
    MatchCondition match_condition,
    typename enable_if< is_match_condition< MatchCondition >::value >::type *  = 0);
  » more...

template<
    typename SyncReadStream,
    typename Allocator,
    typename MatchCondition>
std::size_t read_until(
    SyncReadStream & s,
    boost::asio::basic_streambuf< Allocator > & b,
    MatchCondition match_condition,
    boost::system::error_code & ec,
    typename enable_if< is_match_condition< MatchCondition >::value >::type *  = 0);
  » more...
Requirements

Header: boost/asio/read_until.hpp

Convenience header: boost/asio.hpp

Read data into a streambuf until it contains a specified delimiter.

template<
    typename SyncReadStream,
    typename Allocator>
std::size_t read_until(
    SyncReadStream & s,
    boost::asio::basic_streambuf< Allocator > & b,
    char delim);

This function is used to read data into the specified streambuf until the streambuf's get area contains the specified delimiter. The call will block until one of the following conditions is true:

  • The get area of the streambuf contains the specified delimiter.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the stream's read_some function. If the streambuf's get area already contains the delimiter, the function returns immediately.

Parameters

s

The stream from which the data is to be read. The type must support the SyncReadStream concept.

b

A streambuf object into which the data will be read.

delim

The delimiter character.

Return Value

The number of bytes in the streambuf's get area up to and including the delimiter.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

After a successful read_until operation, the streambuf may contain additional data beyond the delimiter. An application will typically leave that data in the streambuf for a subsequent read_until operation to examine.

Example

To read data into a streambuf until a newline is encountered:

boost::asio::streambuf b;
boost::asio::read_until(s, b, '\n');
std::istream is(&b);
std::string line;
std::getline(is, line);

After the read_until operation completes successfully, the buffer b contains the delimiter:

{ 'a', 'b', ..., 'c', '\n', 'd', 'e', ... }

The call to std::getline then extracts the data up to and including the delimiter, so that the string line contains:

{ 'a', 'b', ..., 'c', '\n' }

The remaining data is left in the buffer b as follows:

{ 'd', 'e', ... }

This data may be the start of a new line, to be extracted by a subsequent read_until operation.

Read data into a streambuf until it contains a specified delimiter.

template<
    typename SyncReadStream,
    typename Allocator>
std::size_t read_until(
    SyncReadStream & s,
    boost::asio::basic_streambuf< Allocator > & b,
    char delim,
    boost::system::error_code & ec);

This function is used to read data into the specified streambuf until the streambuf's get area contains the specified delimiter. The call will block until one of the following conditions is true:

  • The get area of the streambuf contains the specified delimiter.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the stream's read_some function. If the streambuf's get area already contains the delimiter, the function returns immediately.

Parameters

s

The stream from which the data is to be read. The type must support the SyncReadStream concept.

b

A streambuf object into which the data will be read.

delim

The delimiter character.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes in the streambuf's get area up to and including the delimiter. Returns 0 if an error occurred.

Remarks

After a successful read_until operation, the streambuf may contain additional data beyond the delimiter. An application will typically leave that data in the streambuf for a subsequent read_until operation to examine.

Read data into a streambuf until it contains a specified delimiter.

template<
    typename SyncReadStream,
    typename Allocator>
std::size_t read_until(
    SyncReadStream & s,
    boost::asio::basic_streambuf< Allocator > & b,
    const std::string & delim);

This function is used to read data into the specified streambuf until the streambuf's get area contains the specified delimiter. The call will block until one of the following conditions is true:

  • The get area of the streambuf contains the specified delimiter.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the stream's read_some function. If the streambuf's get area already contains the delimiter, the function returns immediately.

Parameters

s

The stream from which the data is to be read. The type must support the SyncReadStream concept.

b

A streambuf object into which the data will be read.

delim

The delimiter string.

Return Value

The number of bytes in the streambuf's get area up to and including the delimiter.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

After a successful read_until operation, the streambuf may contain additional data beyond the delimiter. An application will typically leave that data in the streambuf for a subsequent read_until operation to examine.

Example

To read data into a streambuf until a newline is encountered:

boost::asio::streambuf b;
boost::asio::read_until(s, b, "\r\n");
std::istream is(&b);
std::string line;
std::getline(is, line);

After the read_until operation completes successfully, the buffer b contains the delimiter:

{ 'a', 'b', ..., 'c', '\r', '\n', 'd', 'e', ... }

The call to std::getline then extracts the data up to and including the delimiter, so that the string line contains:

{ 'a', 'b', ..., 'c', '\r', '\n' }

The remaining data is left in the buffer b as follows:

{ 'd', 'e', ... }

This data may be the start of a new line, to be extracted by a subsequent read_until operation.

Read data into a streambuf until it contains a specified delimiter.

template<
    typename SyncReadStream,
    typename Allocator>
std::size_t read_until(
    SyncReadStream & s,
    boost::asio::basic_streambuf< Allocator > & b,
    const std::string & delim,
    boost::system::error_code & ec);

This function is used to read data into the specified streambuf until the streambuf's get area contains the specified delimiter. The call will block until one of the following conditions is true:

  • The get area of the streambuf contains the specified delimiter.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the stream's read_some function. If the streambuf's get area already contains the delimiter, the function returns immediately.

Parameters

s

The stream from which the data is to be read. The type must support the SyncReadStream concept.

b

A streambuf object into which the data will be read.

delim

The delimiter string.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes in the streambuf's get area up to and including the delimiter. Returns 0 if an error occurred.

Remarks

After a successful read_until operation, the streambuf may contain additional data beyond the delimiter. An application will typically leave that data in the streambuf for a subsequent read_until operation to examine.

Read data into a streambuf until some part of the data it contains matches a regular expression.

template<
    typename SyncReadStream,
    typename Allocator>
std::size_t read_until(
    SyncReadStream & s,
    boost::asio::basic_streambuf< Allocator > & b,
    const boost::regex & expr);

This function is used to read data into the specified streambuf until the streambuf's get area contains some data that matches a regular expression. The call will block until one of the following conditions is true:

  • A substring of the streambuf's get area matches the regular expression.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the stream's read_some function. If the streambuf's get area already contains data that matches the regular expression, the function returns immediately.

Parameters

s

The stream from which the data is to be read. The type must support the SyncReadStream concept.

b

A streambuf object into which the data will be read.

expr

The regular expression.

Return Value

The number of bytes in the streambuf's get area up to and including the substring that matches the regular expression.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

After a successful read_until operation, the streambuf may contain additional data beyond that which matched the regular expression. An application will typically leave that data in the streambuf for a subsequent read_until operation to examine.

Example

To read data into a streambuf until a CR-LF sequence is encountered:

boost::asio::streambuf b;
boost::asio::read_until(s, b, boost::regex("\r\n"));
std::istream is(&b);
std::string line;
std::getline(is, line);

After the read_until operation completes successfully, the buffer b contains the data which matched the regular expression:

{ 'a', 'b', ..., 'c', '\r', '\n', 'd', 'e', ... }

The call to std::getline then extracts the data up to and including the match, so that the string line contains:

{ 'a', 'b', ..., 'c', '\r', '\n' }

The remaining data is left in the buffer b as follows:

{ 'd', 'e', ... }

This data may be the start of a new line, to be extracted by a subsequent read_until operation.

Read data into a streambuf until some part of the data it contains matches a regular expression.

template<
    typename SyncReadStream,
    typename Allocator>
std::size_t read_until(
    SyncReadStream & s,
    boost::asio::basic_streambuf< Allocator > & b,
    const boost::regex & expr,
    boost::system::error_code & ec);

This function is used to read data into the specified streambuf until the streambuf's get area contains some data that matches a regular expression. The call will block until one of the following conditions is true:

  • A substring of the streambuf's get area matches the regular expression.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the stream's read_some function. If the streambuf's get area already contains data that matches the regular expression, the function returns immediately.

Parameters

s

The stream from which the data is to be read. The type must support the SyncReadStream concept.

b

A streambuf object into which the data will be read.

expr

The regular expression.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes in the streambuf's get area up to and including the substring that matches the regular expression. Returns 0 if an error occurred.

Remarks

After a successful read_until operation, the streambuf may contain additional data beyond that which matched the regular expression. An application will typically leave that data in the streambuf for a subsequent read_until operation to examine.

Read data into a streambuf until a function object indicates a match.

template<
    typename SyncReadStream,
    typename Allocator,
    typename MatchCondition>
std::size_t read_until(
    SyncReadStream & s,
    boost::asio::basic_streambuf< Allocator > & b,
    MatchCondition match_condition,
    typename enable_if< is_match_condition< MatchCondition >::value >::type *  = 0);

This function is used to read data into the specified streambuf until a user-defined match condition function object, when applied to the data contained in the streambuf, indicates a successful match. The call will block until one of the following conditions is true:

  • The match condition function object returns a std::pair where the second element evaluates to true.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the stream's read_some function. If the match condition function object already indicates a match, the function returns immediately.

Parameters

s

The stream from which the data is to be read. The type must support the SyncReadStream concept.

b

A streambuf object into which the data will be read.

match_condition

The function object to be called to determine whether a match exists. The signature of the function object must be:

pair<iterator, bool> match_condition(iterator begin, iterator end);

where iterator represents the type:

buffers_iterator<basic_streambuf<Allocator>::const_buffers_type>

The iterator parameters begin and end define the range of bytes to be scanned to determine whether there is a match. The first member of the return value is an iterator marking one-past-the-end of the bytes that have been consumed by the match function. This iterator is used to calculate the begin parameter for any subsequent invocation of the match condition. The second member of the return value is true if a match has been found, false otherwise.

Return Value

The number of bytes in the streambuf's get area that have been fully consumed by the match function.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

After a successful read_until operation, the streambuf may contain additional data beyond that which matched the function object. An application will typically leave that data in the streambuf for a subsequent

The default implementation of the is_match_condition type trait evaluates to true for function pointers and function objects with a result_type typedef. It must be specialised for other user-defined function objects.

Examples

To read data into a streambuf until whitespace is encountered:

typedef boost::asio::buffers_iterator<
    boost::asio::streambuf::const_buffers_type> iterator;

std::pair<iterator, bool>
match_whitespace(iterator begin, iterator end)
{
  iterator i = begin;
  while (i != end)
    if (std::isspace(*i++))
      return std::make_pair(i, true);
  return std::make_pair(i, false);
}
...
boost::asio::streambuf b;
boost::asio::read_until(s, b, match_whitespace);

To read data into a streambuf until a matching character is found:

class match_char
{
public:
  explicit match_char(char c) : c_(c) {}

  template <typename Iterator>
  std::pair<Iterator, bool> operator()(
      Iterator begin, Iterator end) const
  {
    Iterator i = begin;
    while (i != end)
      if (c_ == *i++)
        return std::make_pair(i, true);
    return std::make_pair(i, false);
  }

private:
  char c_;
};

namespace asio {
  template <> struct is_match_condition<match_char>
    : public boost::true_type {};
} // namespace asio
...
boost::asio::streambuf b;
boost::asio::read_until(s, b, match_char('a'));

Read data into a streambuf until a function object indicates a match.

template<
    typename SyncReadStream,
    typename Allocator,
    typename MatchCondition>
std::size_t read_until(
    SyncReadStream & s,
    boost::asio::basic_streambuf< Allocator > & b,
    MatchCondition match_condition,
    boost::system::error_code & ec,
    typename enable_if< is_match_condition< MatchCondition >::value >::type *  = 0);

This function is used to read data into the specified streambuf until a user-defined match condition function object, when applied to the data contained in the streambuf, indicates a successful match. The call will block until one of the following conditions is true:

  • The match condition function object returns a std::pair where the second element evaluates to true.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the stream's read_some function. If the match condition function object already indicates a match, the function returns immediately.

Parameters

s

The stream from which the data is to be read. The type must support the SyncReadStream concept.

b

A streambuf object into which the data will be read.

match_condition

The function object to be called to determine whether a match exists. The signature of the function object must be:

pair<iterator, bool> match_condition(iterator begin, iterator end);

where iterator represents the type:

buffers_iterator<basic_streambuf<Allocator>::const_buffers_type>

The iterator parameters begin and end define the range of bytes to be scanned to determine whether there is a match. The first member of the return value is an iterator marking one-past-the-end of the bytes that have been consumed by the match function. This iterator is used to calculate the begin parameter for any subsequent invocation of the match condition. The second member of the return value is true if a match has been found, false otherwise.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes in the streambuf's get area that have been fully consumed by the match function. Returns 0 if an error occurred.

Remarks

After a successful read_until operation, the streambuf may contain additional data beyond that which matched the function object. An application will typically leave that data in the streambuf for a subsequent

The default implementation of the is_match_condition type trait evaluates to true for function pointers and function objects with a result_type typedef. It must be specialised for other user-defined function objects.

Default service implementation for a sequenced packet socket.

template<
    typename Protocol>
class seq_packet_socket_service :
  public io_service::service
Types

Name

Description

endpoint_type

The endpoint type.

implementation_type

The type of a sequenced packet socket implementation.

native_handle_type

The native socket type.

native_type

(Deprecated: Use native_handle_type.) The native socket type.

protocol_type

The protocol type.

Member Functions

Name

Description

assign

Assign an existing native socket to a sequenced packet socket.

async_connect

Start an asynchronous connect.

async_receive

Start an asynchronous receive.

async_send

Start an asynchronous send.

at_mark

Determine whether the socket is at the out-of-band data mark.

available

Determine the number of bytes available for reading.

bind

Bind the sequenced packet socket to the specified local endpoint.

cancel

Cancel all asynchronous operations associated with the socket.

close

Close a sequenced packet socket implementation.

connect

Connect the sequenced packet socket to the specified endpoint.

construct

Construct a new sequenced packet socket implementation.

converting_move_construct

Move-construct a new sequenced packet socket implementation from another protocol type.

destroy

Destroy a sequenced packet socket implementation.

get_io_service

Get the io_service object that owns the service.

get_option

Get a socket option.

io_control

Perform an IO control command on the socket.

is_open

Determine whether the socket is open.

local_endpoint

Get the local endpoint.

move_assign

Move-assign from another sequenced packet socket implementation.

move_construct

Move-construct a new sequenced packet socket implementation.

native

(Deprecated: Use native_handle().) Get the native socket implementation.

native_handle

Get the native socket implementation.

native_non_blocking

Gets the non-blocking mode of the native socket implementation.

Sets the non-blocking mode of the native socket implementation.

non_blocking

Gets the non-blocking mode of the socket.

Sets the non-blocking mode of the socket.

open

Open a sequenced packet socket.

receive

Receive some data from the peer.

remote_endpoint

Get the remote endpoint.

send

Send the given data to the peer.

seq_packet_socket_service

Construct a new sequenced packet socket service for the specified io_service.

set_option

Set a socket option.

shutdown

Disable sends or receives on the socket.

Data Members

Name

Description

id

The unique service identifier.

Requirements

Header: boost/asio/seq_packet_socket_service.hpp

Convenience header: boost/asio.hpp

Assign an existing native socket to a sequenced packet socket.

boost::system::error_code assign(
    implementation_type & impl,
    const protocol_type & protocol,
    const native_handle_type & native_socket,
    boost::system::error_code & ec);

Start an asynchronous connect.

template<
    typename ConnectHandler>
void-or-deduced async_connect(
    implementation_type & impl,
    const endpoint_type & peer_endpoint,
    ConnectHandler handler);

Start an asynchronous receive.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_receive(
    implementation_type & impl,
    const MutableBufferSequence & buffers,
    socket_base::message_flags in_flags,
    socket_base::message_flags & out_flags,
    ReadHandler handler);

Start an asynchronous send.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_send(
    implementation_type & impl,
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags,
    WriteHandler handler);

Determine whether the socket is at the out-of-band data mark.

bool at_mark(
    const implementation_type & impl,
    boost::system::error_code & ec) const;

Determine the number of bytes available for reading.

std::size_t available(
    const implementation_type & impl,
    boost::system::error_code & ec) const;

Bind the sequenced packet socket to the specified local endpoint.

boost::system::error_code bind(
    implementation_type & impl,
    const endpoint_type & endpoint,
    boost::system::error_code & ec);

Cancel all asynchronous operations associated with the socket.

boost::system::error_code cancel(
    implementation_type & impl,
    boost::system::error_code & ec);

Close a sequenced packet socket implementation.

boost::system::error_code close(
    implementation_type & impl,
    boost::system::error_code & ec);

Connect the sequenced packet socket to the specified endpoint.

boost::system::error_code connect(
    implementation_type & impl,
    const endpoint_type & peer_endpoint,
    boost::system::error_code & ec);

Construct a new sequenced packet socket implementation.

void construct(
    implementation_type & impl);

Move-construct a new sequenced packet socket implementation from another protocol type.

template<
    typename Protocol1>
void converting_move_construct(
    implementation_type & impl,
    typename seq_packet_socket_service< Protocol1 >::implementation_type & other_impl,
    typename enable_if< is_convertible< Protocol1, Protocol >::value >::type *  = 0);

Destroy a sequenced packet socket implementation.

void destroy(
    implementation_type & impl);

The endpoint type.

typedef Protocol::endpoint endpoint_type;
Requirements

Header: boost/asio/seq_packet_socket_service.hpp

Convenience header: boost/asio.hpp

Inherited from io_service.

Get the io_service object that owns the service.

boost::asio::io_service & get_io_service();

Get a socket option.

template<
    typename GettableSocketOption>
boost::system::error_code get_option(
    const implementation_type & impl,
    GettableSocketOption & option,
    boost::system::error_code & ec) const;

The unique service identifier.

static boost::asio::io_service::id id;

The type of a sequenced packet socket implementation.

typedef implementation_defined implementation_type;
Requirements

Header: boost/asio/seq_packet_socket_service.hpp

Convenience header: boost/asio.hpp

Perform an IO control command on the socket.

template<
    typename IoControlCommand>
boost::system::error_code io_control(
    implementation_type & impl,
    IoControlCommand & command,
    boost::system::error_code & ec);

Determine whether the socket is open.

bool is_open(
    const implementation_type & impl) const;

Get the local endpoint.

endpoint_type local_endpoint(
    const implementation_type & impl,
    boost::system::error_code & ec) const;

Move-assign from another sequenced packet socket implementation.

void move_assign(
    implementation_type & impl,
    seq_packet_socket_service & other_service,
    implementation_type & other_impl);

Move-construct a new sequenced packet socket implementation.

void move_construct(
    implementation_type & impl,
    implementation_type & other_impl);

(Deprecated: Use native_handle().) Get the native socket implementation.

native_type native(
    implementation_type & impl);

Get the native socket implementation.

native_handle_type native_handle(
    implementation_type & impl);

The native socket type.

typedef implementation_defined native_handle_type;
Requirements

Header: boost/asio/seq_packet_socket_service.hpp

Convenience header: boost/asio.hpp

Gets the non-blocking mode of the native socket implementation.

bool native_non_blocking(
    const implementation_type & impl) const;
  » more...

Sets the non-blocking mode of the native socket implementation.

boost::system::error_code native_non_blocking(
    implementation_type & impl,
    bool mode,
    boost::system::error_code & ec);
  » more...

Gets the non-blocking mode of the native socket implementation.

bool native_non_blocking(
    const implementation_type & impl) const;

Sets the non-blocking mode of the native socket implementation.

boost::system::error_code native_non_blocking(
    implementation_type & impl,
    bool mode,
    boost::system::error_code & ec);

(Deprecated: Use native_handle_type.) The native socket type.

typedef implementation_defined native_type;
Requirements

Header: boost/asio/seq_packet_socket_service.hpp

Convenience header: boost/asio.hpp

Gets the non-blocking mode of the socket.

bool non_blocking(
    const implementation_type & impl) const;
  » more...

Sets the non-blocking mode of the socket.

boost::system::error_code non_blocking(
    implementation_type & impl,
    bool mode,
    boost::system::error_code & ec);
  » more...

Gets the non-blocking mode of the socket.

bool non_blocking(
    const implementation_type & impl) const;

Sets the non-blocking mode of the socket.

boost::system::error_code non_blocking(
    implementation_type & impl,
    bool mode,
    boost::system::error_code & ec);

Open a sequenced packet socket.

boost::system::error_code open(
    implementation_type & impl,
    const protocol_type & protocol,
    boost::system::error_code & ec);

The protocol type.

typedef Protocol protocol_type;
Requirements

Header: boost/asio/seq_packet_socket_service.hpp

Convenience header: boost/asio.hpp

Receive some data from the peer.

template<
    typename MutableBufferSequence>
std::size_t receive(
    implementation_type & impl,
    const MutableBufferSequence & buffers,
    socket_base::message_flags in_flags,
    socket_base::message_flags & out_flags,
    boost::system::error_code & ec);

Get the remote endpoint.

endpoint_type remote_endpoint(
    const implementation_type & impl,
    boost::system::error_code & ec) const;

Send the given data to the peer.

template<
    typename ConstBufferSequence>
std::size_t send(
    implementation_type & impl,
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags,
    boost::system::error_code & ec);

Construct a new sequenced packet socket service for the specified io_service.

seq_packet_socket_service(
    boost::asio::io_service & io_service);

Set a socket option.

template<
    typename SettableSocketOption>
boost::system::error_code set_option(
    implementation_type & impl,
    const SettableSocketOption & option,
    boost::system::error_code & ec);

Disable sends or receives on the socket.

boost::system::error_code shutdown(
    implementation_type & impl,
    socket_base::shutdown_type what,
    boost::system::error_code & ec);

Typedef for the typical usage of a serial port.

typedef basic_serial_port serial_port;
Types

Name

Description

implementation_type

The underlying implementation type of I/O object.

lowest_layer_type

A basic_serial_port is always the lowest layer.

native_handle_type

The native representation of a serial port.

native_type

(Deprecated: Use native_handle_type.) The native representation of a serial port.

service_type

The type of the service that will be used to provide I/O operations.

Member Functions

Name

Description

assign

Assign an existing native serial port to the serial port.

async_read_some

Start an asynchronous read.

async_write_some

Start an asynchronous write.

basic_serial_port

Construct a basic_serial_port without opening it.

Construct and open a basic_serial_port.

Construct a basic_serial_port on an existing native serial port.

Move-construct a basic_serial_port from another.

cancel

Cancel all asynchronous operations associated with the serial port.

close

Close the serial port.

get_io_service

Get the io_service associated with the object.

get_option

Get an option from the serial port.

is_open

Determine whether the serial port is open.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native serial port representation.

native_handle

Get the native serial port representation.

open

Open the serial port using the specified device name.

operator=

Move-assign a basic_serial_port from another.

read_some

Read some data from the serial port.

send_break

Send a break sequence to the serial port.

set_option

Set an option on the serial port.

write_some

Write some data to the serial port.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_serial_port class template provides functionality that is common to all serial ports.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/serial_port.hpp

Convenience header: boost/asio.hpp

The serial_port_base class is used as a base for the basic_serial_port class template so that we have a common place to define the serial port options.

class serial_port_base
Types

Name

Description

baud_rate

Serial port option to permit changing the baud rate.

character_size

Serial port option to permit changing the character size.

flow_control

Serial port option to permit changing the flow control.

parity

Serial port option to permit changing the parity.

stop_bits

Serial port option to permit changing the number of stop bits.

Protected Member Functions

Name

Description

~serial_port_base

Protected destructor to prevent deletion through this type.

Requirements

Header: boost/asio/serial_port_base.hpp

Convenience header: boost/asio.hpp

Protected destructor to prevent deletion through this type.

~serial_port_base();

Serial port option to permit changing the baud rate.

class baud_rate
Member Functions

Name

Description

baud_rate

load

store

value

Implements changing the baud rate for a given serial port.

Requirements

Header: boost/asio/serial_port_base.hpp

Convenience header: boost/asio.hpp

baud_rate(
    unsigned int rate = 0);

boost::system::error_code load(
    const BOOST_ASIO_OPTION_STORAGE & storage,
    boost::system::error_code & ec);

boost::system::error_code store(
    BOOST_ASIO_OPTION_STORAGE & storage,
    boost::system::error_code & ec) const;

unsigned int value() const;

Serial port option to permit changing the character size.

class character_size
Member Functions

Name

Description

character_size

load

store

value

Implements changing the character size for a given serial port.

Requirements

Header: boost/asio/serial_port_base.hpp

Convenience header: boost/asio.hpp

character_size(
    unsigned int t = 8);

boost::system::error_code load(
    const BOOST_ASIO_OPTION_STORAGE & storage,
    boost::system::error_code & ec);

boost::system::error_code store(
    BOOST_ASIO_OPTION_STORAGE & storage,
    boost::system::error_code & ec) const;

unsigned int value() const;

Serial port option to permit changing the flow control.

class flow_control
Types

Name

Description

type

Member Functions

Name

Description

flow_control

load

store

value

Implements changing the flow control for a given serial port.

Requirements

Header: boost/asio/serial_port_base.hpp

Convenience header: boost/asio.hpp

flow_control(
    type t = none);

boost::system::error_code load(
    const BOOST_ASIO_OPTION_STORAGE & storage,
    boost::system::error_code & ec);

boost::system::error_code store(
    BOOST_ASIO_OPTION_STORAGE & storage,
    boost::system::error_code & ec) const;

enum type

Values

none
software
hardware

Serial port option to permit changing the parity.

class parity
Types

Name

Description

type

Member Functions

Name

Description

load

parity

store

value

Implements changing the parity for a given serial port.

Requirements

Header: boost/asio/serial_port_base.hpp

Convenience header: boost/asio.hpp

boost::system::error_code load(
    const BOOST_ASIO_OPTION_STORAGE & storage,
    boost::system::error_code & ec);

parity(
    type t = none);

boost::system::error_code store(
    BOOST_ASIO_OPTION_STORAGE & storage,
    boost::system::error_code & ec) const;

enum type

Values

none
odd
even

type value() const;

Serial port option to permit changing the number of stop bits.

class stop_bits
Types

Name

Description

type

Member Functions

Name

Description

load

stop_bits

store

value

Implements changing the number of stop bits for a given serial port.

Requirements

Header: boost/asio/serial_port_base.hpp

Convenience header: boost/asio.hpp

boost::system::error_code load(
    const BOOST_ASIO_OPTION_STORAGE & storage,
    boost::system::error_code & ec);

stop_bits(
    type t = one);

boost::system::error_code store(
    BOOST_ASIO_OPTION_STORAGE & storage,
    boost::system::error_code & ec) const;

enum type

Values

one
onepointfive
two

Default service implementation for a serial port.

class serial_port_service :
  public io_service::service
Types

Name

Description

implementation_type

The type of a serial port implementation.

native_handle_type

The native handle type.

native_type

(Deprecated: Use native_handle_type.) The native handle type.

Member Functions

Name

Description

assign

Assign an existing native handle to a serial port.

async_read_some

Start an asynchronous read.

async_write_some

Start an asynchronous write.

cancel

Cancel all asynchronous operations associated with the handle.

close

Close a serial port implementation.

construct

Construct a new serial port implementation.

destroy

Destroy a serial port implementation.

get_io_service

Get the io_service object that owns the service.

get_option

Get a serial port option.

is_open

Determine whether the handle is open.

move_assign

Move-assign from another serial port implementation.

move_construct

Move-construct a new serial port implementation.

native

(Deprecated: Use native_handle().) Get the native handle implementation.

native_handle

Get the native handle implementation.

open

Open a serial port.

read_some

Read some data from the stream.

send_break

Send a break sequence to the serial port.

serial_port_service

Construct a new serial port service for the specified io_service.

set_option

Set a serial port option.

write_some

Write the given data to the stream.

Data Members

Name

Description

id

The unique service identifier.

Requirements

Header: boost/asio/serial_port_service.hpp

Convenience header: boost/asio.hpp

Assign an existing native handle to a serial port.

boost::system::error_code assign(
    implementation_type & impl,
    const native_handle_type & handle,
    boost::system::error_code & ec);

Start an asynchronous read.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_read_some(
    implementation_type & impl,
    const MutableBufferSequence & buffers,
    ReadHandler handler);

Start an asynchronous write.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_write_some(
    implementation_type & impl,
    const ConstBufferSequence & buffers,
    WriteHandler handler);

Cancel all asynchronous operations associated with the handle.

boost::system::error_code cancel(
    implementation_type & impl,
    boost::system::error_code & ec);

Close a serial port implementation.

boost::system::error_code close(
    implementation_type & impl,
    boost::system::error_code & ec);

Construct a new serial port implementation.

void construct(
    implementation_type & impl);

Destroy a serial port implementation.

void destroy(
    implementation_type & impl);

Inherited from io_service.

Get the io_service object that owns the service.

boost::asio::io_service & get_io_service();

Get a serial port option.

template<
    typename GettableSerialPortOption>
boost::system::error_code get_option(
    const implementation_type & impl,
    GettableSerialPortOption & option,
    boost::system::error_code & ec) const;

The unique service identifier.

static boost::asio::io_service::id id;

The type of a serial port implementation.

typedef implementation_defined implementation_type;
Requirements

Header: boost/asio/serial_port_service.hpp

Convenience header: boost/asio.hpp

Determine whether the handle is open.

bool is_open(
    const implementation_type & impl) const;

Move-assign from another serial port implementation.

void move_assign(
    implementation_type & impl,
    serial_port_service & other_service,
    implementation_type & other_impl);

Move-construct a new serial port implementation.

void move_construct(
    implementation_type & impl,
    implementation_type & other_impl);

(Deprecated: Use native_handle().) Get the native handle implementation.

native_type native(
    implementation_type & impl);

Get the native handle implementation.

native_handle_type native_handle(
    implementation_type & impl);

The native handle type.

typedef implementation_defined native_handle_type;
Requirements

Header: boost/asio/serial_port_service.hpp

Convenience header: boost/asio.hpp

(Deprecated: Use native_handle_type.) The native handle type.

typedef implementation_defined native_type;
Requirements

Header: boost/asio/serial_port_service.hpp

Convenience header: boost/asio.hpp

Open a serial port.

boost::system::error_code open(
    implementation_type & impl,
    const std::string & device,
    boost::system::error_code & ec);

Read some data from the stream.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    implementation_type & impl,
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);

Send a break sequence to the serial port.

boost::system::error_code send_break(
    implementation_type & impl,
    boost::system::error_code & ec);

Construct a new serial port service for the specified io_service.

serial_port_service(
    boost::asio::io_service & io_service);

Set a serial port option.

template<
    typename SettableSerialPortOption>
boost::system::error_code set_option(
    implementation_type & impl,
    const SettableSerialPortOption & option,
    boost::system::error_code & ec);

Write the given data to the stream.

template<
    typename ConstBufferSequence>
std::size_t write_some(
    implementation_type & impl,
    const ConstBufferSequence & buffers,
    boost::system::error_code & ec);

Exception thrown when trying to add a duplicate service to an io_service.

class service_already_exists
Member Functions

Name

Description

service_already_exists

Requirements

Header: boost/asio/io_service.hpp

Convenience header: boost/asio.hpp

Typedef for the typical usage of a signal set.

typedef basic_signal_set signal_set;
Types

Name

Description

implementation_type

The underlying implementation type of I/O object.

service_type

The type of the service that will be used to provide I/O operations.

Member Functions

Name

Description

add

Add a signal to a signal_set.

async_wait

Start an asynchronous operation to wait for a signal to be delivered.

basic_signal_set

Construct a signal set without adding any signals.

Construct a signal set and add one signal.

Construct a signal set and add two signals.

Construct a signal set and add three signals.

cancel

Cancel all operations associated with the signal set.

clear

Remove all signals from a signal_set.

get_io_service

Get the io_service associated with the object.

remove

Remove a signal from a signal_set.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_signal_set class template provides the ability to perform an asynchronous wait for one or more signals to occur.

Most applications will use the signal_set typedef.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Example

Performing an asynchronous wait:

void handler(
    const boost::system::error_code& error,
    int signal_number)
{
  if (!error)
  {
    // A signal occurred.
  }
}

...

// Construct a signal set registered for process termination.
boost::asio::signal_set signals(io_service, SIGINT, SIGTERM);

// Start an asynchronous wait for one of the signals to occur.
signals.async_wait(handler);
Queueing of signal notifications

If a signal is registered with a signal_set, and the signal occurs when there are no waiting handlers, then the signal notification is queued. The next async_wait operation on that signal_set will dequeue the notification. If multiple notifications are queued, subsequent async_wait operations dequeue them one at a time. Signal notifications are dequeued in order of ascending signal number.

If a signal number is removed from a signal_set (using the remove or erase member functions) then any queued notifications for that signal are discarded.

Multiple registration of signals

The same signal number may be registered with different signal_set objects. When the signal occurs, one handler is called for each signal_set object.

Note that multiple registration only works for signals that are registered using Asio. The application must not also register a signal handler using functions such as signal() or sigaction().

Signal masking on POSIX platforms

POSIX allows signals to be blocked using functions such as sigprocmask() and pthread_sigmask(). For signals to be delivered, programs must ensure that any signals registered using signal_set objects are unblocked in at least one thread.

Requirements

Header: boost/asio/signal_set.hpp

Convenience header: boost/asio.hpp

Default service implementation for a signal set.

class signal_set_service :
  public io_service::service
Types

Name

Description

implementation_type

The type of a signal set implementation.

Member Functions

Name

Description

add

Add a signal to a signal_set.

async_wait

cancel

Cancel all operations associated with the signal set.

clear

Remove all signals from a signal_set.

construct

Construct a new signal set implementation.

destroy

Destroy a signal set implementation.

get_io_service

Get the io_service object that owns the service.

remove

Remove a signal to a signal_set.

signal_set_service

Construct a new signal set service for the specified io_service.

Data Members

Name

Description

id

The unique service identifier.

Requirements

Header: boost/asio/signal_set_service.hpp

Convenience header: boost/asio.hpp

Add a signal to a signal_set.

boost::system::error_code add(
    implementation_type & impl,
    int signal_number,
    boost::system::error_code & ec);

template<
    typename SignalHandler>
void-or-deduced async_wait(
    implementation_type & impl,
    SignalHandler handler);

Cancel all operations associated with the signal set.

boost::system::error_code cancel(
    implementation_type & impl,
    boost::system::error_code & ec);

Remove all signals from a signal_set.

boost::system::error_code clear(
    implementation_type & impl,
    boost::system::error_code & ec);

Construct a new signal set implementation.

void construct(
    implementation_type & impl);

Destroy a signal set implementation.

void destroy(
    implementation_type & impl);

Inherited from io_service.

Get the io_service object that owns the service.

boost::asio::io_service & get_io_service();

The unique service identifier.

static boost::asio::io_service::id id;

The type of a signal set implementation.

typedef implementation_defined implementation_type;
Requirements

Header: boost/asio/signal_set_service.hpp

Convenience header: boost/asio.hpp

Remove a signal to a signal_set.

boost::system::error_code remove(
    implementation_type & impl,
    int signal_number,
    boost::system::error_code & ec);

Construct a new signal set service for the specified io_service.

signal_set_service(
    boost::asio::io_service & io_service);

Default service implementation for a socket acceptor.

template<
    typename Protocol>
class socket_acceptor_service :
  public io_service::service
Types

Name

Description

endpoint_type

The endpoint type.

implementation_type

The native type of the socket acceptor.

native_handle_type

The native acceptor type.

native_type

(Deprecated: Use native_handle_type.) The native acceptor type.

protocol_type

The protocol type.

Member Functions

Name

Description

accept

Accept a new connection.

assign

Assign an existing native acceptor to a socket acceptor.

async_accept

Start an asynchronous accept.

bind

Bind the socket acceptor to the specified local endpoint.

cancel

Cancel all asynchronous operations associated with the acceptor.

close

Close a socket acceptor implementation.

construct

Construct a new socket acceptor implementation.

converting_move_construct

Move-construct a new socket acceptor implementation from another protocol type.

destroy

Destroy a socket acceptor implementation.

get_io_service

Get the io_service object that owns the service.

get_option

Get a socket option.

io_control

Perform an IO control command on the socket.

is_open

Determine whether the acceptor is open.

listen

Place the socket acceptor into the state where it will listen for new connections.

local_endpoint

Get the local endpoint.

move_assign

Move-assign from another socket acceptor implementation.

move_construct

Move-construct a new socket acceptor implementation.

native

(Deprecated: Use native_handle().) Get the native acceptor implementation.

native_handle

Get the native acceptor implementation.

native_non_blocking

Gets the non-blocking mode of the native acceptor implementation.

Sets the non-blocking mode of the native acceptor implementation.

non_blocking

Gets the non-blocking mode of the acceptor.

Sets the non-blocking mode of the acceptor.

open

Open a new socket acceptor implementation.

set_option

Set a socket option.

socket_acceptor_service

Construct a new socket acceptor service for the specified io_service.

Data Members

Name

Description

id

The unique service identifier.

Requirements

Header: boost/asio/socket_acceptor_service.hpp

Convenience header: boost/asio.hpp

Accept a new connection.

template<
    typename Protocol1,
    typename SocketService>
boost::system::error_code accept(
    implementation_type & impl,
    basic_socket< Protocol1, SocketService > & peer,
    endpoint_type * peer_endpoint,
    boost::system::error_code & ec,
    typename enable_if< is_convertible< Protocol, Protocol1 >::value >::type *  = 0);

Assign an existing native acceptor to a socket acceptor.

boost::system::error_code assign(
    implementation_type & impl,
    const protocol_type & protocol,
    const native_handle_type & native_acceptor,
    boost::system::error_code & ec);

Start an asynchronous accept.

template<
    typename Protocol1,
    typename SocketService,
    typename AcceptHandler>
void-or-deduced async_accept(
    implementation_type & impl,
    basic_socket< Protocol1, SocketService > & peer,
    endpoint_type * peer_endpoint,
    AcceptHandler handler,
    typename enable_if< is_convertible< Protocol, Protocol1 >::value >::type *  = 0);

Bind the socket acceptor to the specified local endpoint.

boost::system::error_code bind(
    implementation_type & impl,
    const endpoint_type & endpoint,
    boost::system::error_code & ec);

Cancel all asynchronous operations associated with the acceptor.

boost::system::error_code cancel(
    implementation_type & impl,
    boost::system::error_code & ec);

Close a socket acceptor implementation.

boost::system::error_code close(
    implementation_type & impl,
    boost::system::error_code & ec);

Construct a new socket acceptor implementation.

void construct(
    implementation_type & impl);

Move-construct a new socket acceptor implementation from another protocol type.

template<
    typename Protocol1>
void converting_move_construct(
    implementation_type & impl,
    typename socket_acceptor_service< Protocol1 >::implementation_type & other_impl,
    typename enable_if< is_convertible< Protocol1, Protocol >::value >::type *  = 0);

Destroy a socket acceptor implementation.

void destroy(
    implementation_type & impl);

The endpoint type.

typedef protocol_type::endpoint endpoint_type;
Requirements

Header: boost/asio/socket_acceptor_service.hpp

Convenience header: boost/asio.hpp

Inherited from io_service.

Get the io_service object that owns the service.

boost::asio::io_service & get_io_service();

Get a socket option.

template<
    typename GettableSocketOption>
boost::system::error_code get_option(
    const implementation_type & impl,
    GettableSocketOption & option,
    boost::system::error_code & ec) const;

The unique service identifier.

static boost::asio::io_service::id id;

The native type of the socket acceptor.

typedef implementation_defined implementation_type;
Requirements

Header: boost/asio/socket_acceptor_service.hpp

Convenience header: boost/asio.hpp

Perform an IO control command on the socket.

template<
    typename IoControlCommand>
boost::system::error_code io_control(
    implementation_type & impl,
    IoControlCommand & command,
    boost::system::error_code & ec);

Determine whether the acceptor is open.

bool is_open(
    const implementation_type & impl) const;

Place the socket acceptor into the state where it will listen for new connections.

boost::system::error_code listen(
    implementation_type & impl,
    int backlog,
    boost::system::error_code & ec);

Get the local endpoint.

endpoint_type local_endpoint(
    const implementation_type & impl,
    boost::system::error_code & ec) const;

Move-assign from another socket acceptor implementation.

void move_assign(
    implementation_type & impl,
    socket_acceptor_service & other_service,
    implementation_type & other_impl);

Move-construct a new socket acceptor implementation.

void move_construct(
    implementation_type & impl,
    implementation_type & other_impl);

(Deprecated: Use native_handle().) Get the native acceptor implementation.

native_type native(
    implementation_type & impl);

Get the native acceptor implementation.

native_handle_type native_handle(
    implementation_type & impl);

The native acceptor type.

typedef implementation_defined native_handle_type;
Requirements

Header: boost/asio/socket_acceptor_service.hpp

Convenience header: boost/asio.hpp

Gets the non-blocking mode of the native acceptor implementation.

bool native_non_blocking(
    const implementation_type & impl) const;
  » more...

Sets the non-blocking mode of the native acceptor implementation.

boost::system::error_code native_non_blocking(
    implementation_type & impl,
    bool mode,
    boost::system::error_code & ec);
  » more...

Gets the non-blocking mode of the native acceptor implementation.

bool native_non_blocking(
    const implementation_type & impl) const;

Sets the non-blocking mode of the native acceptor implementation.

boost::system::error_code native_non_blocking(
    implementation_type & impl,
    bool mode,
    boost::system::error_code & ec);

(Deprecated: Use native_handle_type.) The native acceptor type.

typedef implementation_defined native_type;
Requirements

Header: boost/asio/socket_acceptor_service.hpp

Convenience header: boost/asio.hpp

Gets the non-blocking mode of the acceptor.

bool non_blocking(
    const implementation_type & impl) const;
  » more...

Sets the non-blocking mode of the acceptor.

boost::system::error_code non_blocking(
    implementation_type & impl,
    bool mode,
    boost::system::error_code & ec);
  » more...

Gets the non-blocking mode of the acceptor.

bool non_blocking(
    const implementation_type & impl) const;

Sets the non-blocking mode of the acceptor.

boost::system::error_code non_blocking(
    implementation_type & impl,
    bool mode,
    boost::system::error_code & ec);

Open a new socket acceptor implementation.

boost::system::error_code open(
    implementation_type & impl,
    const protocol_type & protocol,
    boost::system::error_code & ec);

The protocol type.

typedef Protocol protocol_type;
Requirements

Header: boost/asio/socket_acceptor_service.hpp

Convenience header: boost/asio.hpp

Set a socket option.

template<
    typename SettableSocketOption>
boost::system::error_code set_option(
    implementation_type & impl,
    const SettableSocketOption & option,
    boost::system::error_code & ec);

Construct a new socket acceptor service for the specified io_service.

socket_acceptor_service(
    boost::asio::io_service & io_service);

The socket_base class is used as a base for the basic_stream_socket and basic_datagram_socket class templates so that we have a common place to define the shutdown_type and enum.

class socket_base
Types

Name

Description

broadcast

Socket option to permit sending of broadcast messages.

bytes_readable

IO control command to get the amount of data that can be read without blocking.

debug

Socket option to enable socket-level debugging.

do_not_route

Socket option to prevent routing, use local interfaces only.

enable_connection_aborted

Socket option to report aborted connections on accept.

keep_alive

Socket option to send keep-alives.

linger

Socket option to specify whether the socket lingers on close if unsent data is present.

message_flags

Bitmask type for flags that can be passed to send and receive operations.

non_blocking_io

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

receive_buffer_size

Socket option for the receive buffer size of a socket.

receive_low_watermark

Socket option for the receive low watermark.

reuse_address

Socket option to allow the socket to be bound to an address that is already in use.

send_buffer_size

Socket option for the send buffer size of a socket.

send_low_watermark

Socket option for the send low watermark.

shutdown_type

Different ways a socket may be shutdown.

Protected Member Functions

Name

Description

~socket_base

Protected destructor to prevent deletion through this type.

Data Members

Name

Description

max_connections

The maximum length of the queue of pending incoming connections.

message_do_not_route

Specify that the data should not be subject to routing.

message_end_of_record

Specifies that the data marks the end of a record.

message_out_of_band

Process out-of-band data.

message_peek

Peek at incoming data without removing it from the input queue.

Requirements

Header: boost/asio/socket_base.hpp

Convenience header: boost/asio.hpp

Socket option to permit sending of broadcast messages.

typedef implementation_defined broadcast;

Implements the SOL_SOCKET/SO_BROADCAST socket option.

Examples

Setting the option:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::broadcast option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::broadcast option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/socket_base.hpp

Convenience header: boost/asio.hpp

IO control command to get the amount of data that can be read without blocking.

typedef implementation_defined bytes_readable;

Implements the FIONREAD IO control command.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::bytes_readable command(true);
socket.io_control(command);
std::size_t bytes_readable = command.get();
Requirements

Header: boost/asio/socket_base.hpp

Convenience header: boost/asio.hpp

Socket option to enable socket-level debugging.

typedef implementation_defined debug;

Implements the SOL_SOCKET/SO_DEBUG socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::debug option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::debug option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/socket_base.hpp

Convenience header: boost/asio.hpp

Socket option to prevent routing, use local interfaces only.

typedef implementation_defined do_not_route;

Implements the SOL_SOCKET/SO_DONTROUTE socket option.

Examples

Setting the option:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::do_not_route option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::udp::socket socket(io_service);
...
boost::asio::socket_base::do_not_route option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/socket_base.hpp

Convenience header: boost/asio.hpp

Socket option to report aborted connections on accept.

typedef implementation_defined enable_connection_aborted;

Implements a custom socket option that determines whether or not an accept operation is permitted to fail with boost::asio::error::connection_aborted. By default the option is false.

Examples

Setting the option:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::enable_connection_aborted option(true);
acceptor.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::enable_connection_aborted option;
acceptor.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/socket_base.hpp

Convenience header: boost/asio.hpp

Socket option to send keep-alives.

typedef implementation_defined keep_alive;

Implements the SOL_SOCKET/SO_KEEPALIVE socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::keep_alive option(true);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::keep_alive option;
socket.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/socket_base.hpp

Convenience header: boost/asio.hpp

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.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::linger option(true, 30);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::linger option;
socket.get_option(option);
bool is_set = option.enabled();
unsigned short timeout = option.timeout();
Requirements

Header: boost/asio/socket_base.hpp

Convenience header: boost/asio.hpp

The maximum length of the queue of pending incoming connections.

static const int max_connections = implementation_defined;

Specify that the data should not be subject to routing.

static const int message_do_not_route = implementation_defined;

Specifies that the data marks the end of a record.

static const int message_end_of_record = implementation_defined;

Bitmask type for flags that can be passed to send and receive operations.

typedef int message_flags;
Requirements

Header: boost/asio/socket_base.hpp

Convenience header: boost/asio.hpp

Process out-of-band data.

static const int message_out_of_band = implementation_defined;

Peek at incoming data without removing it from the input queue.

static const int message_peek = implementation_defined;

(Deprecated: Use non_blocking().) IO control command to set the blocking mode of the socket.

typedef implementation_defined non_blocking_io;

Implements the FIONBIO IO control command.

Example
boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::non_blocking_io command(true);
socket.io_control(command);
Requirements

Header: boost/asio/socket_base.hpp

Convenience header: boost/asio.hpp

Socket option for the receive buffer size of a socket.

typedef implementation_defined receive_buffer_size;

Implements the SOL_SOCKET/SO_RCVBUF socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_buffer_size option(8192);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_buffer_size option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/socket_base.hpp

Convenience header: boost/asio.hpp

Socket option for the receive low watermark.

typedef implementation_defined receive_low_watermark;

Implements the SOL_SOCKET/SO_RCVLOWAT socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_low_watermark option(1024);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::receive_low_watermark option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/socket_base.hpp

Convenience header: boost/asio.hpp

Socket option to allow the socket to be bound to an address that is already in use.

typedef implementation_defined reuse_address;

Implements the SOL_SOCKET/SO_REUSEADDR socket option.

Examples

Setting the option:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::reuse_address option(true);
acceptor.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::acceptor acceptor(io_service);
...
boost::asio::socket_base::reuse_address option;
acceptor.get_option(option);
bool is_set = option.value();
Requirements

Header: boost/asio/socket_base.hpp

Convenience header: boost/asio.hpp

Socket option for the send buffer size of a socket.

typedef implementation_defined send_buffer_size;

Implements the SOL_SOCKET/SO_SNDBUF socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_buffer_size option(8192);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_buffer_size option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/socket_base.hpp

Convenience header: boost/asio.hpp

Socket option for the send low watermark.

typedef implementation_defined send_low_watermark;

Implements the SOL_SOCKET/SO_SNDLOWAT socket option.

Examples

Setting the option:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_low_watermark option(1024);
socket.set_option(option);

Getting the current option value:

boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::send_low_watermark option;
socket.get_option(option);
int size = option.value();
Requirements

Header: boost/asio/socket_base.hpp

Convenience header: boost/asio.hpp

Different ways a socket may be shutdown.

enum shutdown_type

Values

shutdown_receive

Shutdown the receive side of the socket.

shutdown_send

Shutdown the send side of the socket.

shutdown_both

Shutdown both send and receive on the socket.

Protected destructor to prevent deletion through this type.

~socket_base();

Start a new stackful coroutine.

template<
    typename Handler,
    typename Function>
void spawn(
    Handler handler,
    Function function,
    const boost::coroutines::attributes & attributes = boost::coroutines::attributes());
  » more...

template<
    typename Handler,
    typename Function>
void spawn(
    basic_yield_context< Handler > ctx,
    Function function,
    const boost::coroutines::attributes & attributes = boost::coroutines::attributes());
  » more...

template<
    typename Function>
void spawn(
    boost::asio::io_service::strand strand,
    Function function,
    const boost::coroutines::attributes & attributes = boost::coroutines::attributes());
  » more...

template<
    typename Function>
void spawn(
    boost::asio::io_service & io_service,
    Function function,
    const boost::coroutines::attributes & attributes = boost::coroutines::attributes());
  » more...

The spawn() function is a high-level wrapper over the Boost.Coroutine library. This function enables programs to implement asynchronous logic in a synchronous manner, as illustrated by the following example:

boost::asio::spawn(my_strand, do_echo);

// ...

void do_echo(boost::asio::yield_context yield)
{
  try
  {
    char data[128];
    for (;;)
    {
      std::size_t length =
        my_socket.async_read_some(
          boost::asio::buffer(data), yield);

      boost::asio::async_write(my_socket,
          boost::asio::buffer(data, length), yield);
    }
  }
  catch (std::exception& e)
  {
    // ...
  }
}
Requirements

Header: boost/asio/spawn.hpp

Convenience header: None

Start a new stackful coroutine, calling the specified handler when it completes.

template<
    typename Handler,
    typename Function>
void spawn(
    Handler handler,
    Function function,
    const boost::coroutines::attributes & attributes = boost::coroutines::attributes());

This function is used to launch a new coroutine.

Parameters

handler

A handler to be called when the coroutine exits. More importantly, the handler provides an execution context (via the the handler invocation hook) for the coroutine. The handler must have the signature:

void handler();

function

The coroutine function. The function must have the signature:

void function(basic_yield_context<Handler> yield);

attributes

Boost.Coroutine attributes used to customise the coroutine.

Start a new stackful coroutine, inheriting the execution context of another.

template<
    typename Handler,
    typename Function>
void spawn(
    basic_yield_context< Handler > ctx,
    Function function,
    const boost::coroutines::attributes & attributes = boost::coroutines::attributes());

This function is used to launch a new coroutine.

Parameters

ctx

Identifies the current coroutine as a parent of the new coroutine. This specifies that the new coroutine should inherit the execution context of the parent. For example, if the parent coroutine is executing in a particular strand, then the new coroutine will execute in the same strand.

function

The coroutine function. The function must have the signature:

void function(basic_yield_context<Handler> yield);

attributes

Boost.Coroutine attributes used to customise the coroutine.

Start a new stackful coroutine that executes in the context of a strand.

template<
    typename Function>
void spawn(
    boost::asio::io_service::strand strand,
    Function function,
    const boost::coroutines::attributes & attributes = boost::coroutines::attributes());

This function is used to launch a new coroutine.

Parameters

strand

Identifies a strand. By starting multiple coroutines on the same strand, the implementation ensures that none of those coroutines can execute simultaneously.

function

The coroutine function. The function must have the signature:

void function(yield_context yield);

attributes

Boost.Coroutine attributes used to customise the coroutine.

Start a new stackful coroutine that executes on a given io_service.

template<
    typename Function>
void spawn(
    boost::asio::io_service & io_service,
    Function function,
    const boost::coroutines::attributes & attributes = boost::coroutines::attributes());

This function is used to launch a new coroutine.

Parameters

io_service

Identifies the io_service that will run the coroutine. The new coroutine is implicitly given its own strand within this io_service.

function

The coroutine function. The function must have the signature:

void function(yield_context yield);

attributes

Boost.Coroutine attributes used to customise the coroutine.

class context :
  public ssl::context_base,
  noncopyable
Types

Name

Description

file_format

File format types.

impl_type

(Deprecated: Use native_handle_type.) The native type of the SSL context.

method

Different methods supported by a context.

native_handle_type

The native handle type of the SSL context.

options

Bitmask type for SSL options.

password_purpose

Purpose of PEM password.

Member Functions

Name

Description

add_certificate_authority

Add certification authority for performing verification.

add_verify_path

Add a directory containing certificate authority files to be used for performing verification.

clear_options

Clear options on the context.

context

Constructor.

Deprecated constructor taking a reference to an io_service object.

Move-construct a context from another.

impl

(Deprecated: Use native_handle().) Get the underlying implementation in the native type.

load_verify_file

Load a certification authority file for performing verification.

native_handle

Get the underlying implementation in the native type.

operator=

Move-assign a context from another.

set_default_verify_paths

Configures the context to use the default directories for finding certification authority certificates.

set_options

Set options on the context.

set_password_callback

Set the password callback.

set_verify_callback

Set the callback used to verify peer certificates.

set_verify_depth

Set the peer verification depth.

set_verify_mode

Set the peer verification mode.

use_certificate

Use a certificate from a memory buffer.

use_certificate_chain

Use a certificate chain from a memory buffer.

use_certificate_chain_file

Use a certificate chain from a file.

use_certificate_file

Use a certificate from a file.

use_private_key

Use a private key from a memory buffer.

use_private_key_file

Use a private key from a file.

use_rsa_private_key

Use an RSA private key from a memory buffer.

use_rsa_private_key_file

Use an RSA private key from a file.

use_tmp_dh

Use the specified memory buffer to obtain the temporary Diffie-Hellman parameters.

use_tmp_dh_file

Use the specified file to obtain the temporary Diffie-Hellman parameters.

~context

Destructor.

Data Members

Name

Description

default_workarounds

Implement various bug workarounds.

no_compression

Disable compression. Compression is disabled by default.

no_sslv2

Disable SSL v2.

no_sslv3

Disable SSL v3.

no_tlsv1

Disable TLS v1.

no_tlsv1_1

Disable TLS v1.1.

no_tlsv1_2

Disable TLS v1.2.

single_dh_use

Always create a new key when using tmp_dh parameters.

Requirements

Header: boost/asio/ssl/context.hpp

Convenience header: boost/asio/ssl.hpp

Add certification authority for performing verification.

void add_certificate_authority(
    const const_buffer & ca);
  » more...

boost::system::error_code add_certificate_authority(
    const const_buffer & ca,
    boost::system::error_code & ec);
  » more...

Add certification authority for performing verification.

void add_certificate_authority(
    const const_buffer & ca);

This function is used to add one trusted certification authority from a memory buffer.

Parameters

ca

The buffer containing the certification authority certificate. The certificate must use the PEM format.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Calls SSL_CTX_get_cert_store and X509_STORE_add_cert.

Add certification authority for performing verification.

boost::system::error_code add_certificate_authority(
    const const_buffer & ca,
    boost::system::error_code & ec);

This function is used to add one trusted certification authority from a memory buffer.

Parameters

ca

The buffer containing the certification authority certificate. The certificate must use the PEM format.

ec

Set to indicate what error occurred, if any.

Remarks

Calls SSL_CTX_get_cert_store and X509_STORE_add_cert.

Add a directory containing certificate authority files to be used for performing verification.

void add_verify_path(
    const std::string & path);
  » more...

boost::system::error_code add_verify_path(
    const std::string & path,
    boost::system::error_code & ec);
  » more...

Add a directory containing certificate authority files to be used for performing verification.

void add_verify_path(
    const std::string & path);

This function is used to specify the name of a directory containing certification authority certificates. Each file in the directory must contain a single certificate. The files must be named using the subject name's hash and an extension of ".0".

Parameters

path

The name of a directory containing the certificates.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Calls SSL_CTX_load_verify_locations.

Add a directory containing certificate authority files to be used for performing verification.

boost::system::error_code add_verify_path(
    const std::string & path,
    boost::system::error_code & ec);

This function is used to specify the name of a directory containing certification authority certificates. Each file in the directory must contain a single certificate. The files must be named using the subject name's hash and an extension of ".0".

Parameters

path

The name of a directory containing the certificates.

ec

Set to indicate what error occurred, if any.

Remarks

Calls SSL_CTX_load_verify_locations.

Clear options on the context.

void clear_options(
    options o);
  » more...

boost::system::error_code clear_options(
    options o,
    boost::system::error_code & ec);
  » more...

Clear options on the context.

void clear_options(
    options o);

This function may be used to configure the SSL options used by the context.

Parameters

o

A bitmask of options. The available option values are defined in the ssl::context_base class. The specified options, if currently enabled on the context, are cleared.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Calls SSL_CTX_clear_options.

Clear options on the context.

boost::system::error_code clear_options(
    options o,
    boost::system::error_code & ec);

This function may be used to configure the SSL options used by the context.

Parameters

o

A bitmask of options. The available option values are defined in the ssl::context_base class. The specified options, if currently enabled on the context, are cleared.

ec

Set to indicate what error occurred, if any.

Remarks

Calls SSL_CTX_clear_options.

Constructor.

explicit context(
    method m);
  » more...

Deprecated constructor taking a reference to an io_service object.

context(
    boost::asio::io_service & ,
    method m);
  » more...

Move-construct a context from another.

context(
    context && other);
  » more...

Constructor.

context(
    method m);

Deprecated constructor taking a reference to an io_service object.

context(
    boost::asio::io_service & ,
    method m);

Move-construct a context from another.

context(
    context && other);

This constructor moves an SSL context from one object to another.

Parameters

other

The other context object from which the move will occur.

Remarks

Following the move, the following operations only are valid for the moved-from object: * Destruction.

  • As a target for move-assignment.

Implement various bug workarounds.

static const long default_workarounds = implementation_defined;

File format types.

enum file_format

Values

asn1

ASN.1 file.

pem

PEM file.

(Deprecated: Use native_handle().) Get the underlying implementation in the native type.

impl_type impl();

This function may be used to obtain the underlying implementation of the context. This is intended to allow access to context functionality that is not otherwise provided.

(Deprecated: Use native_handle_type.) The native type of the SSL context.

typedef SSL_CTX * impl_type;
Requirements

Header: boost/asio/ssl/context.hpp

Convenience header: boost/asio/ssl.hpp

Load a certification authority file for performing verification.

void load_verify_file(
    const std::string & filename);
  » more...

boost::system::error_code load_verify_file(
    const std::string & filename,
    boost::system::error_code & ec);
  » more...

Load a certification authority file for performing verification.

void load_verify_file(
    const std::string & filename);

This function is used to load one or more trusted certification authorities from a file.

Parameters

filename

The name of a file containing certification authority certificates in PEM format.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Calls SSL_CTX_load_verify_locations.

Load a certification authority file for performing verification.

boost::system::error_code load_verify_file(
    const std::string & filename,
    boost::system::error_code & ec);

This function is used to load the certificates for one or more trusted certification authorities from a file.

Parameters

filename

The name of a file containing certification authority certificates in PEM format.

ec

Set to indicate what error occurred, if any.

Remarks

Calls SSL_CTX_load_verify_locations.

Different methods supported by a context.

enum method

Values

sslv2

Generic SSL version 2.

sslv2_client

SSL version 2 client.

sslv2_server

SSL version 2 server.

sslv3

Generic SSL version 3.

sslv3_client

SSL version 3 client.

sslv3_server

SSL version 3 server.

tlsv1

Generic TLS version 1.

tlsv1_client

TLS version 1 client.

tlsv1_server

TLS version 1 server.

sslv23

Generic SSL/TLS.

sslv23_client

SSL/TLS client.

sslv23_server

SSL/TLS server.

tlsv11

Generic TLS version 1.1.

tlsv11_client

TLS version 1.1 client.

tlsv11_server

TLS version 1.1 server.

tlsv12

Generic TLS version 1.2.

tlsv12_client

TLS version 1.2 client.

tlsv12_server

TLS version 1.2 server.

Get the underlying implementation in the native type.

native_handle_type native_handle();

This function may be used to obtain the underlying implementation of the context. This is intended to allow access to context functionality that is not otherwise provided.

The native handle type of the SSL context.

typedef SSL_CTX * native_handle_type;
Requirements

Header: boost/asio/ssl/context.hpp

Convenience header: boost/asio/ssl.hpp

Disable compression. Compression is disabled by default.

static const long no_compression = implementation_defined;

Disable SSL v2.

static const long no_sslv2 = implementation_defined;

Disable SSL v3.

static const long no_sslv3 = implementation_defined;

Disable TLS v1.

static const long no_tlsv1 = implementation_defined;

Disable TLS v1.1.

static const long no_tlsv1_1 = implementation_defined;

Disable TLS v1.2.

static const long no_tlsv1_2 = implementation_defined;

Move-assign a context from another.

context & operator=(
    context && other);

This assignment operator moves an SSL context from one object to another.

Parameters

other

The other context object from which the move will occur.

Remarks

Following the move, the following operations only are valid for the moved-from object: * Destruction.

  • As a target for move-assignment.

Bitmask type for SSL options.

typedef long options;
Requirements

Header: boost/asio/ssl/context.hpp

Convenience header: boost/asio/ssl.hpp

Purpose of PEM password.

enum password_purpose

Values

for_reading

The password is needed for reading/decryption.

for_writing

The password is needed for writing/encryption.

Configures the context to use the default directories for finding certification authority certificates.

void set_default_verify_paths();
  » more...

boost::system::error_code set_default_verify_paths(
    boost::system::error_code & ec);
  » more...

Configures the context to use the default directories for finding certification authority certificates.

void set_default_verify_paths();

This function specifies that the context should use the default, system-dependent directories for locating certification authority certificates.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Calls SSL_CTX_set_default_verify_paths.

Configures the context to use the default directories for finding certification authority certificates.

boost::system::error_code set_default_verify_paths(
    boost::system::error_code & ec);

This function specifies that the context should use the default, system-dependent directories for locating certification authority certificates.

Parameters

ec

Set to indicate what error occurred, if any.

Remarks

Calls SSL_CTX_set_default_verify_paths.

Set options on the context.

void set_options(
    options o);
  » more...

boost::system::error_code set_options(
    options o,
    boost::system::error_code & ec);
  » more...

Set options on the context.

void set_options(
    options o);

This function may be used to configure the SSL options used by the context.

Parameters

o

A bitmask of options. The available option values are defined in the ssl::context_base class. The options are bitwise-ored with any existing value for the options.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Calls SSL_CTX_set_options.

Set options on the context.

boost::system::error_code set_options(
    options o,
    boost::system::error_code & ec);

This function may be used to configure the SSL options used by the context.

Parameters

o

A bitmask of options. The available option values are defined in the ssl::context_base class. The options are bitwise-ored with any existing value for the options.

ec

Set to indicate what error occurred, if any.

Remarks

Calls SSL_CTX_set_options.

Set the password callback.

template<
    typename PasswordCallback>
void set_password_callback(
    PasswordCallback callback);
  » more...

template<
    typename PasswordCallback>
boost::system::error_code set_password_callback(
    PasswordCallback callback,
    boost::system::error_code & ec);
  » more...

Set the password callback.

template<
    typename PasswordCallback>
void set_password_callback(
    PasswordCallback callback);

This function is used to specify a callback function to obtain password information about an encrypted key in PEM format.

Parameters

callback

The function object to be used for obtaining the password. The function signature of the handler must be:

std::string password_callback(
  std::size_t max_length,  // The maximum size for a password.
  password_purpose purpose // Whether password is for reading or writing.
);

The return value of the callback is a string containing the password.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Calls SSL_CTX_set_default_passwd_cb.

Set the password callback.

template<
    typename PasswordCallback>
boost::system::error_code set_password_callback(
    PasswordCallback callback,
    boost::system::error_code & ec);

This function is used to specify a callback function to obtain password information about an encrypted key in PEM format.

Parameters

callback

The function object to be used for obtaining the password. The function signature of the handler must be:

std::string password_callback(
  std::size_t max_length,  // The maximum size for a password.
  password_purpose purpose // Whether password is for reading or writing.
);

The return value of the callback is a string containing the password.

ec

Set to indicate what error occurred, if any.

Remarks

Calls SSL_CTX_set_default_passwd_cb.

Set the callback used to verify peer certificates.

template<
    typename VerifyCallback>
void set_verify_callback(
    VerifyCallback callback);
  » more...

template<
    typename VerifyCallback>
boost::system::error_code set_verify_callback(
    VerifyCallback callback,
    boost::system::error_code & ec);
  » more...

Set the callback used to verify peer certificates.

template<
    typename VerifyCallback>
void set_verify_callback(
    VerifyCallback callback);

This function is used to specify a callback function that will be called by the implementation when it needs to verify a peer certificate.

Parameters

callback

The function object to be used for verifying a certificate. The function signature of the handler must be:

bool verify_callback(
  bool preverified, // True if the certificate passed pre-verification.
  verify_context& ctx // The peer certificate and other context.
);

The return value of the callback is true if the certificate has passed verification, false otherwise.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Calls SSL_CTX_set_verify.

Set the callback used to verify peer certificates.

template<
    typename VerifyCallback>
boost::system::error_code set_verify_callback(
    VerifyCallback callback,
    boost::system::error_code & ec);

This function is used to specify a callback function that will be called by the implementation when it needs to verify a peer certificate.

Parameters

callback

The function object to be used for verifying a certificate. The function signature of the handler must be:

bool verify_callback(
  bool preverified, // True if the certificate passed pre-verification.
  verify_context& ctx // The peer certificate and other context.
);

The return value of the callback is true if the certificate has passed verification, false otherwise.

ec

Set to indicate what error occurred, if any.

Remarks

Calls SSL_CTX_set_verify.

Set the peer verification depth.

void set_verify_depth(
    int depth);
  » more...

boost::system::error_code set_verify_depth(
    int depth,
    boost::system::error_code & ec);
  » more...

Set the peer verification depth.

void set_verify_depth(
    int depth);

This function may be used to configure the maximum verification depth allowed by the context.

Parameters

depth

Maximum depth for the certificate chain verification that shall be allowed.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Calls SSL_CTX_set_verify_depth.

Set the peer verification depth.

boost::system::error_code set_verify_depth(
    int depth,
    boost::system::error_code & ec);

This function may be used to configure the maximum verification depth allowed by the context.

Parameters

depth

Maximum depth for the certificate chain verification that shall be allowed.

ec

Set to indicate what error occurred, if any.

Remarks

Calls SSL_CTX_set_verify_depth.

Set the peer verification mode.

void set_verify_mode(
    verify_mode v);
  » more...

boost::system::error_code set_verify_mode(
    verify_mode v,
    boost::system::error_code & ec);
  » more...

Set the peer verification mode.

void set_verify_mode(
    verify_mode v);

This function may be used to configure the peer verification mode used by the context.

Parameters

v

A bitmask of peer verification modes. See ssl::verify_mode for available values.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Calls SSL_CTX_set_verify.

Set the peer verification mode.

boost::system::error_code set_verify_mode(
    verify_mode v,
    boost::system::error_code & ec);

This function may be used to configure the peer verification mode used by the context.

Parameters

v

A bitmask of peer verification modes. See ssl::verify_mode for available values.

ec

Set to indicate what error occurred, if any.

Remarks

Calls SSL_CTX_set_verify.

Always create a new key when using tmp_dh parameters.

static const long single_dh_use = implementation_defined;

Use a certificate from a memory buffer.

void use_certificate(
    const const_buffer & certificate,
    file_format format);
  » more...

boost::system::error_code use_certificate(
    const const_buffer & certificate,
    file_format format,
    boost::system::error_code & ec);
  » more...

Use a certificate from a memory buffer.

void use_certificate(
    const const_buffer & certificate,
    file_format format);

This function is used to load a certificate into the context from a buffer.

Parameters

certificate

The buffer containing the certificate.

format

The certificate format (ASN.1 or PEM).

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Calls SSL_CTX_use_certificate or SSL_CTX_use_certificate_ASN1.

Use a certificate from a memory buffer.

boost::system::error_code use_certificate(
    const const_buffer & certificate,
    file_format format,
    boost::system::error_code & ec);

This function is used to load a certificate into the context from a buffer.

Parameters

certificate

The buffer containing the certificate.

format

The certificate format (ASN.1 or PEM).

ec

Set to indicate what error occurred, if any.

Remarks

Calls SSL_CTX_use_certificate or SSL_CTX_use_certificate_ASN1.

Use a certificate chain from a memory buffer.

void use_certificate_chain(
    const const_buffer & chain);
  » more...

boost::system::error_code use_certificate_chain(
    const const_buffer & chain,
    boost::system::error_code & ec);
  » more...

Use a certificate chain from a memory buffer.

void use_certificate_chain(
    const const_buffer & chain);

This function is used to load a certificate chain into the context from a buffer.

Parameters

chain

The buffer containing the certificate chain. The certificate chain must use the PEM format.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Calls SSL_CTX_use_certificate and SSL_CTX_add_extra_chain_cert.

Use a certificate chain from a memory buffer.

boost::system::error_code use_certificate_chain(
    const const_buffer & chain,
    boost::system::error_code & ec);

This function is used to load a certificate chain into the context from a buffer.

Parameters

chain

The buffer containing the certificate chain. The certificate chain must use the PEM format.

ec

Set to indicate what error occurred, if any.

Remarks

Calls SSL_CTX_use_certificate and SSL_CTX_add_extra_chain_cert.

Use a certificate chain from a file.

void use_certificate_chain_file(
    const std::string & filename);
  » more...

boost::system::error_code use_certificate_chain_file(
    const std::string & filename,
    boost::system::error_code & ec);
  » more...

Use a certificate chain from a file.

void use_certificate_chain_file(
    const std::string & filename);

This function is used to load a certificate chain into the context from a file.

Parameters

filename

The name of the file containing the certificate. The file must use the PEM format.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Calls SSL_CTX_use_certificate_chain_file.

Use a certificate chain from a file.

boost::system::error_code use_certificate_chain_file(
    const std::string & filename,
    boost::system::error_code & ec);

This function is used to load a certificate chain into the context from a file.

Parameters

filename

The name of the file containing the certificate. The file must use the PEM format.

ec

Set to indicate what error occurred, if any.

Remarks

Calls SSL_CTX_use_certificate_chain_file.

Use a certificate from a file.

void use_certificate_file(
    const std::string & filename,
    file_format format);
  » more...

boost::system::error_code use_certificate_file(
    const std::string & filename,
    file_format format,
    boost::system::error_code & ec);
  » more...

Use a certificate from a file.

void use_certificate_file(
    const std::string & filename,
    file_format format);

This function is used to load a certificate into the context from a file.

Parameters

filename

The name of the file containing the certificate.

format

The file format (ASN.1 or PEM).

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Calls SSL_CTX_use_certificate_file.

Use a certificate from a file.

boost::system::error_code use_certificate_file(
    const std::string & filename,
    file_format format,
    boost::system::error_code & ec);

This function is used to load a certificate into the context from a file.

Parameters

filename

The name of the file containing the certificate.

format

The file format (ASN.1 or PEM).

ec

Set to indicate what error occurred, if any.

Remarks

Calls SSL_CTX_use_certificate_file.

Use a private key from a memory buffer.

void use_private_key(
    const const_buffer & private_key,
    file_format format);
  » more...

boost::system::error_code use_private_key(
    const const_buffer & private_key,
    file_format format,
    boost::system::error_code & ec);
  » more...

Use a private key from a memory buffer.

void use_private_key(
    const const_buffer & private_key,
    file_format format);

This function is used to load a private key into the context from a buffer.

Parameters

private_key

The buffer containing the private key.

format

The private key format (ASN.1 or PEM).

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Calls SSL_CTX_use_PrivateKey or SSL_CTX_use_PrivateKey_ASN1.

Use a private key from a memory buffer.

boost::system::error_code use_private_key(
    const const_buffer & private_key,
    file_format format,
    boost::system::error_code & ec);

This function is used to load a private key into the context from a buffer.

Parameters

private_key

The buffer containing the private key.

format

The private key format (ASN.1 or PEM).

ec

Set to indicate what error occurred, if any.

Remarks

Calls SSL_CTX_use_PrivateKey or SSL_CTX_use_PrivateKey_ASN1.

Use a private key from a file.

void use_private_key_file(
    const std::string & filename,
    file_format format);
  » more...

boost::system::error_code use_private_key_file(
    const std::string & filename,
    file_format format,
    boost::system::error_code & ec);
  » more...

Use a private key from a file.

void use_private_key_file(
    const std::string & filename,
    file_format format);

This function is used to load a private key into the context from a file.

Parameters

filename

The name of the file containing the private key.

format

The file format (ASN.1 or PEM).

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Calls SSL_CTX_use_PrivateKey_file.

Use a private key from a file.

boost::system::error_code use_private_key_file(
    const std::string & filename,
    file_format format,
    boost::system::error_code & ec);

This function is used to load a private key into the context from a file.

Parameters

filename

The name of the file containing the private key.

format

The file format (ASN.1 or PEM).

ec

Set to indicate what error occurred, if any.

Remarks

Calls SSL_CTX_use_PrivateKey_file.

Use an RSA private key from a memory buffer.

void use_rsa_private_key(
    const const_buffer & private_key,
    file_format format);
  » more...

boost::system::error_code use_rsa_private_key(
    const const_buffer & private_key,
    file_format format,
    boost::system::error_code & ec);
  » more...

Use an RSA private key from a memory buffer.

void use_rsa_private_key(
    const const_buffer & private_key,
    file_format format);

This function is used to load an RSA private key into the context from a buffer.

Parameters

private_key

The buffer containing the RSA private key.

format

The private key format (ASN.1 or PEM).

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Calls SSL_CTX_use_RSAPrivateKey or SSL_CTX_use_RSAPrivateKey_ASN1.

Use an RSA private key from a memory buffer.

boost::system::error_code use_rsa_private_key(
    const const_buffer & private_key,
    file_format format,
    boost::system::error_code & ec);

This function is used to load an RSA private key into the context from a buffer.

Parameters

private_key

The buffer containing the RSA private key.

format

The private key format (ASN.1 or PEM).

ec

Set to indicate what error occurred, if any.

Remarks

Calls SSL_CTX_use_RSAPrivateKey or SSL_CTX_use_RSAPrivateKey_ASN1.

Use an RSA private key from a file.

void use_rsa_private_key_file(
    const std::string & filename,
    file_format format);
  » more...

boost::system::error_code use_rsa_private_key_file(
    const std::string & filename,
    file_format format,
    boost::system::error_code & ec);
  » more...

Use an RSA private key from a file.

void use_rsa_private_key_file(
    const std::string & filename,
    file_format format);

This function is used to load an RSA private key into the context from a file.

Parameters

filename

The name of the file containing the RSA private key.

format

The file format (ASN.1 or PEM).

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Calls SSL_CTX_use_RSAPrivateKey_file.

Use an RSA private key from a file.

boost::system::error_code use_rsa_private_key_file(
    const std::string & filename,
    file_format format,
    boost::system::error_code & ec);

This function is used to load an RSA private key into the context from a file.

Parameters

filename

The name of the file containing the RSA private key.

format

The file format (ASN.1 or PEM).

ec

Set to indicate what error occurred, if any.

Remarks

Calls SSL_CTX_use_RSAPrivateKey_file.

Use the specified memory buffer to obtain the temporary Diffie-Hellman parameters.

void use_tmp_dh(
    const const_buffer & dh);
  » more...

boost::system::error_code use_tmp_dh(
    const const_buffer & dh,
    boost::system::error_code & ec);
  » more...

Use the specified memory buffer to obtain the temporary Diffie-Hellman parameters.

void use_tmp_dh(
    const const_buffer & dh);

This function is used to load Diffie-Hellman parameters into the context from a buffer.

Parameters

dh

The memory buffer containing the Diffie-Hellman parameters. The buffer must use the PEM format.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Calls SSL_CTX_set_tmp_dh.

Use the specified memory buffer to obtain the temporary Diffie-Hellman parameters.

boost::system::error_code use_tmp_dh(
    const const_buffer & dh,
    boost::system::error_code & ec);

This function is used to load Diffie-Hellman parameters into the context from a buffer.

Parameters

dh

The memory buffer containing the Diffie-Hellman parameters. The buffer must use the PEM format.

ec

Set to indicate what error occurred, if any.

Remarks

Calls SSL_CTX_set_tmp_dh.

Use the specified file to obtain the temporary Diffie-Hellman parameters.

void use_tmp_dh_file(
    const std::string & filename);
  » more...

boost::system::error_code use_tmp_dh_file(
    const std::string & filename,
    boost::system::error_code & ec);
  » more...

Use the specified file to obtain the temporary Diffie-Hellman parameters.

void use_tmp_dh_file(
    const std::string & filename);

This function is used to load Diffie-Hellman parameters into the context from a file.

Parameters

filename

The name of the file containing the Diffie-Hellman parameters. The file must use the PEM format.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Calls SSL_CTX_set_tmp_dh.

Use the specified file to obtain the temporary Diffie-Hellman parameters.

boost::system::error_code use_tmp_dh_file(
    const std::string & filename,
    boost::system::error_code & ec);

This function is used to load Diffie-Hellman parameters into the context from a file.

Parameters

filename

The name of the file containing the Diffie-Hellman parameters. The file must use the PEM format.

ec

Set to indicate what error occurred, if any.

Remarks

Calls SSL_CTX_set_tmp_dh.

Destructor.

~context();

The ssl::context_base class is used as a base for the basic_context class template so that we have a common place to define various enums.

class context_base
Types

Name

Description

file_format

File format types.

method

Different methods supported by a context.

options

Bitmask type for SSL options.

password_purpose

Purpose of PEM password.

Protected Member Functions

Name

Description

~context_base

Protected destructor to prevent deletion through this type.

Data Members

Name

Description

default_workarounds

Implement various bug workarounds.

no_compression

Disable compression. Compression is disabled by default.

no_sslv2

Disable SSL v2.

no_sslv3

Disable SSL v3.

no_tlsv1

Disable TLS v1.

no_tlsv1_1

Disable TLS v1.1.

no_tlsv1_2

Disable TLS v1.2.

single_dh_use

Always create a new key when using tmp_dh parameters.

Requirements

Header: boost/asio/ssl/context_base.hpp

Convenience header: boost/asio/ssl.hpp

Implement various bug workarounds.

static const long default_workarounds = implementation_defined;

File format types.

enum file_format

Values

asn1

ASN.1 file.

pem

PEM file.

Different methods supported by a context.

enum method

Values

sslv2

Generic SSL version 2.

sslv2_client

SSL version 2 client.

sslv2_server

SSL version 2 server.

sslv3

Generic SSL version 3.

sslv3_client

SSL version 3 client.

sslv3_server

SSL version 3 server.

tlsv1

Generic TLS version 1.

tlsv1_client

TLS version 1 client.

tlsv1_server

TLS version 1 server.

sslv23

Generic SSL/TLS.

sslv23_client

SSL/TLS client.

sslv23_server

SSL/TLS server.

tlsv11

Generic TLS version 1.1.

tlsv11_client

TLS version 1.1 client.

tlsv11_server

TLS version 1.1 server.

tlsv12

Generic TLS version 1.2.

tlsv12_client

TLS version 1.2 client.

tlsv12_server

TLS version 1.2 server.

Disable compression. Compression is disabled by default.

static const long no_compression = implementation_defined;

Disable SSL v2.

static const long no_sslv2 = implementation_defined;

Disable SSL v3.

static const long no_sslv3 = implementation_defined;

Disable TLS v1.

static const long no_tlsv1 = implementation_defined;

Disable TLS v1.1.

static const long no_tlsv1_1 = implementation_defined;

Disable TLS v1.2.

static const long no_tlsv1_2 = implementation_defined;

Bitmask type for SSL options.

typedef long options;
Requirements

Header: boost/asio/ssl/context_base.hpp

Convenience header: boost/asio/ssl.hpp

Purpose of PEM password.

enum password_purpose

Values

for_reading

The password is needed for reading/decryption.

for_writing

The password is needed for writing/encryption.

Always create a new key when using tmp_dh parameters.

static const long single_dh_use = implementation_defined;

Protected destructor to prevent deletion through this type.

~context_base();

const boost::system::error_category & get_stream_category();
Requirements

Header: boost/asio/ssl/error.hpp

Convenience header: boost/asio/ssl.hpp

boost::system::error_code make_error_code(
    stream_errors e);
Requirements

Header: boost/asio/ssl/error.hpp

Convenience header: boost/asio/ssl.hpp

static const boost::system::error_category & stream_category = boost::asio::ssl::error::get_stream_category();
Requirements

Header: boost/asio/ssl/error.hpp

Convenience header: boost/asio/ssl.hpp

enum stream_errors

Values

stream_truncated

The underlying stream closed before the ssl stream gracefully shut down.

Requirements

Header: boost/asio/ssl/error.hpp

Convenience header: boost/asio/ssl.hpp

Verifies a certificate against a hostname according to the rules described in RFC 2818.

class rfc2818_verification
Types

Name

Description

result_type

The type of the function object's result.

Member Functions

Name

Description

operator()

Perform certificate verification.

rfc2818_verification

Constructor.

Example

The following example shows how to synchronously open a secure connection to a given host name:

using boost::asio::ip::tcp;
namespace ssl = boost::asio::ssl;
typedef ssl::stream<tcp::socket> ssl_socket;

// Create a context that uses the default paths for finding CA certificates.
ssl::context ctx(ssl::context::sslv23);
ctx.set_default_verify_paths();

// Open a socket and connect it to the remote host.
boost::asio::io_service io_service;
ssl_socket sock(io_service, ctx);
tcp::resolver resolver(io_service);
tcp::resolver::query query("host.name", "https");
boost::asio::connect(sock.lowest_layer(), resolver.resolve(query));
sock.lowest_layer().set_option(tcp::no_delay(true));

// Perform SSL handshake and verify the remote host's certificate.
sock.set_verify_mode(ssl::verify_peer);
sock.set_verify_callback(ssl::rfc2818_verification("host.name"));
sock.handshake(ssl_socket::client);

// ... read and write as normal ...
Requirements

Header: boost/asio/ssl/rfc2818_verification.hpp

Convenience header: boost/asio/ssl.hpp

Perform certificate verification.

bool operator()(
    bool preverified,
    verify_context & ctx) const;

The type of the function object's result.

typedef bool result_type;
Requirements

Header: boost/asio/ssl/rfc2818_verification.hpp

Convenience header: boost/asio/ssl.hpp

Constructor.

rfc2818_verification(
    const std::string & host);

Provides stream-oriented functionality using SSL.

template<
    typename Stream>
class stream :
  public ssl::stream_base,
  noncopyable
Types

Name

Description

impl_struct

Structure for use with deprecated impl_type.

handshake_type

Different handshake types.

impl_type

(Deprecated: Use native_handle_type.) The underlying implementation type.

lowest_layer_type

The type of the lowest layer.

native_handle_type

The native handle type of the SSL stream.

next_layer_type

The type of the next layer.

Member Functions

Name

Description

async_handshake

Start an asynchronous SSL handshake.

async_read_some

Start an asynchronous read.

async_shutdown

Asynchronously shut down SSL on the stream.

async_write_some

Start an asynchronous write.

get_io_service

Get the io_service associated with the object.

handshake

Perform SSL handshaking.

impl

(Deprecated: Use native_handle().) Get the underlying implementation in the native type.

lowest_layer

Get a reference to the lowest layer.

native_handle

Get the underlying implementation in the native type.

next_layer

Get a reference to the next layer.

read_some

Read some data from the stream.

set_verify_callback

Set the callback used to verify peer certificates.

set_verify_depth

Set the peer verification depth.

set_verify_mode

Set the peer verification mode.

shutdown

Shut down SSL on the stream.

stream

Construct a stream.

write_some

Write some data to the stream.

~stream

Destructor.

The stream class template provides asynchronous and blocking stream-oriented functionality using SSL.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe. The application must also ensure that all asynchronous operations are performed within the same implicit or explicit strand.

Example

To use the SSL stream template with an ip::tcp::socket, you would write:

boost::asio::io_service io_service;
boost::asio::ssl::context ctx(boost::asio::ssl::context::sslv23);
boost::asio::ssl::stream<asio:ip::tcp::socket> sock(io_service, ctx);
Requirements

Header: boost/asio/ssl/stream.hpp

Convenience header: boost/asio/ssl.hpp

Start an asynchronous SSL handshake.

template<
    typename HandshakeHandler>
void-or-deduced async_handshake(
    handshake_type type,
    HandshakeHandler handler);
  » more...

template<
    typename ConstBufferSequence,
    typename BufferedHandshakeHandler>
void-or-deduced async_handshake(
    handshake_type type,
    const ConstBufferSequence & buffers,
    BufferedHandshakeHandler handler);
  » more...

Start an asynchronous SSL handshake.

template<
    typename HandshakeHandler>
void-or-deduced async_handshake(
    handshake_type type,
    HandshakeHandler handler);

This function is used to asynchronously perform an SSL handshake on the stream. This function call always returns immediately.

Parameters

type

The type of handshaking to be performed, i.e. as a client or as a server.

handler

The handler to be called when the handshake operation completes. Copies will be made of the handler as required. The equivalent function signature of the handler must be:

void handler(
  const boost::system::error_code& error // Result of operation.
);

Start an asynchronous SSL handshake.

template<
    typename ConstBufferSequence,
    typename BufferedHandshakeHandler>
void-or-deduced async_handshake(
    handshake_type type,
    const ConstBufferSequence & buffers,
    BufferedHandshakeHandler handler);

This function is used to asynchronously perform an SSL handshake on the stream. This function call always returns immediately.

Parameters

type

The type of handshaking to be performed, i.e. as a client or as a server.

buffers

The buffered data to be reused for the handshake. Although the buffers object may be copied as necessary, ownership of the underlying buffers is retained by the caller, which must guarantee that they remain valid until the handler is called.

handler

The handler to be called when the handshake operation completes. Copies will be made of the handler as required. The equivalent function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred // Amount of buffers used in handshake.
);

Start an asynchronous read.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_read_some(
    const MutableBufferSequence & buffers,
    ReadHandler handler);

This function is used to asynchronously read one or more bytes of data from the stream. The function call always returns immediately.

Parameters

buffers

The buffers into which the data will be read. Although the buffers object may be copied as necessary, ownership of the underlying buffers is retained by the caller, which must guarantee that they remain valid until the handler is called.

handler

The handler to be called when the read operation completes. Copies will be made of the handler as required. The equivalent function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes read.
);

Remarks

The async_read_some operation may not read all of the requested number of bytes. Consider using the async_read function if you need to ensure that the requested amount of data is read before the asynchronous operation completes.

Asynchronously shut down SSL on the stream.

template<
    typename ShutdownHandler>
void-or-deduced async_shutdown(
    ShutdownHandler handler);

This function is used to asynchronously shut down SSL on the stream. This function call always returns immediately.

Parameters

handler

The handler to be called when the handshake operation completes. Copies will be made of the handler as required. The equivalent function signature of the handler must be:

void handler(
  const boost::system::error_code& error // Result of operation.
);

Start an asynchronous write.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_write_some(
    const ConstBufferSequence & buffers,
    WriteHandler handler);

This function is used to asynchronously write one or more bytes of data to the stream. The function call always returns immediately.

Parameters

buffers

The data to be written to the stream. Although the buffers object may be copied as necessary, ownership of the underlying buffers is retained by the caller, which must guarantee that they remain valid until the handler is called.

handler

The handler to be called when the write operation completes. Copies will be made of the handler as required. The equivalent function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes written.
);

Remarks

The async_write_some operation may not transmit all of the data to the peer. Consider using the async_write function if you need to ensure that all data is written before the blocking operation completes.

Get the io_service associated with the object.

boost::asio::io_service & get_io_service();

This function may be used to obtain the io_service object that the stream uses to dispatch handlers for asynchronous operations.

Return Value

A reference to the io_service object that stream will use to dispatch handlers. Ownership is not transferred to the caller.

Perform SSL handshaking.

void handshake(
    handshake_type type);
  » more...

boost::system::error_code handshake(
    handshake_type type,
    boost::system::error_code & ec);
  » more...

template<
    typename ConstBufferSequence>
void handshake(
    handshake_type type,
    const ConstBufferSequence & buffers);
  » more...

template<
    typename ConstBufferSequence>
boost::system::error_code handshake(
    handshake_type type,
    const ConstBufferSequence & buffers,
    boost::system::error_code & ec);
  » more...

Perform SSL handshaking.

void handshake(
    handshake_type type);

This function is used to perform SSL handshaking on the stream. The function call will block until handshaking is complete or an error occurs.

Parameters

type

The type of handshaking to be performed, i.e. as a client or as a server.

Exceptions

boost::system::system_error

Thrown on failure.

Perform SSL handshaking.

boost::system::error_code handshake(
    handshake_type type,
    boost::system::error_code & ec);

This function is used to perform SSL handshaking on the stream. The function call will block until handshaking is complete or an error occurs.

Parameters

type

The type of handshaking to be performed, i.e. as a client or as a server.

ec

Set to indicate what error occurred, if any.

Perform SSL handshaking.

template<
    typename ConstBufferSequence>
void handshake(
    handshake_type type,
    const ConstBufferSequence & buffers);

This function is used to perform SSL handshaking on the stream. The function call will block until handshaking is complete or an error occurs.

Parameters

type

The type of handshaking to be performed, i.e. as a client or as a server.

buffers

The buffered data to be reused for the handshake.

Exceptions

boost::system::system_error

Thrown on failure.

Perform SSL handshaking.

template<
    typename ConstBufferSequence>
boost::system::error_code handshake(
    handshake_type type,
    const ConstBufferSequence & buffers,
    boost::system::error_code & ec);

This function is used to perform SSL handshaking on the stream. The function call will block until handshaking is complete or an error occurs.

Parameters

type

The type of handshaking to be performed, i.e. as a client or as a server.

buffers

The buffered data to be reused for the handshake.

ec

Set to indicate what error occurred, if any.

Different handshake types.

enum handshake_type

Values

client

Perform handshaking as a client.

server

Perform handshaking as a server.

(Deprecated: Use native_handle().) Get the underlying implementation in the native type.

impl_type impl();

This function may be used to obtain the underlying implementation of the context. This is intended to allow access to stream functionality that is not otherwise provided.

(Deprecated: Use native_handle_type.) The underlying implementation type.

typedef impl_struct * impl_type;
Requirements

Header: boost/asio/ssl/stream.hpp

Convenience header: boost/asio/ssl.hpp

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();
  » more...

const lowest_layer_type & lowest_layer() const;
  » more...

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();

This function returns a reference to the lowest layer in a stack of stream layers.

Return Value

A reference to the lowest layer in the stack of stream layers. Ownership is not transferred to the caller.

Get a reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;

This function returns a reference to the lowest layer in a stack of stream layers.

Return Value

A reference to the lowest layer in the stack of stream layers. Ownership is not transferred to the caller.

The type of the lowest layer.

typedef next_layer_type::lowest_layer_type lowest_layer_type;
Requirements

Header: boost/asio/ssl/stream.hpp

Convenience header: boost/asio/ssl.hpp

Get the underlying implementation in the native type.

native_handle_type native_handle();

This function may be used to obtain the underlying implementation of the context. This is intended to allow access to context functionality that is not otherwise provided.

Example

The native_handle() function returns a pointer of type SSL* that is suitable for passing to functions such as SSL_get_verify_result and SSL_get_peer_certificate:

boost::asio::ssl::stream<asio:ip::tcp::socket> sock(io_service, ctx);

// ... establish connection and perform handshake ...

if (X509* cert = SSL_get_peer_certificate(sock.native_handle()))
{
  if (SSL_get_verify_result(sock.native_handle()) == X509_V_OK)
  {
    // ...
  }
}

The native handle type of the SSL stream.

typedef SSL * native_handle_type;
Requirements

Header: boost/asio/ssl/stream.hpp

Convenience header: boost/asio/ssl.hpp

Get a reference to the next layer.

const next_layer_type & next_layer() const;
  » more...

next_layer_type & next_layer();
  » more...

Get a reference to the next layer.

const next_layer_type & next_layer() const;

This function returns a reference to the next layer in a stack of stream layers.

Return Value

A reference to the next layer in the stack of stream layers. Ownership is not transferred to the caller.

Get a reference to the next layer.

next_layer_type & next_layer();

This function returns a reference to the next layer in a stack of stream layers.

Return Value

A reference to the next layer in the stack of stream layers. Ownership is not transferred to the caller.

The type of the next layer.

typedef remove_reference< Stream >::type next_layer_type;
Requirements

Header: boost/asio/ssl/stream.hpp

Convenience header: boost/asio/ssl.hpp

Read some data from the stream.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers);
  » more...

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);
  » more...

Read some data from the stream.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers);

This function is used to read data from the stream. The function call will block until one or more bytes of data has been read successfully, or until an error occurs.

Parameters

buffers

The buffers into which the data will be read.

Return Value

The number of bytes read.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

The read_some operation may not read all of the requested number of bytes. Consider using the read function if you need to ensure that the requested amount of data is read before the blocking operation completes.

Read some data from the stream.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);

This function is used to read data from the stream. The function call will block until one or more bytes of data has been read successfully, or until an error occurs.

Parameters

buffers

The buffers into which the data will be read.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes read. Returns 0 if an error occurred.

Remarks

The read_some operation may not read all of the requested number of bytes. Consider using the read function if you need to ensure that the requested amount of data is read before the blocking operation completes.

Set the callback used to verify peer certificates.

template<
    typename VerifyCallback>
void set_verify_callback(
    VerifyCallback callback);
  » more...

template<
    typename VerifyCallback>
boost::system::error_code set_verify_callback(
    VerifyCallback callback,
    boost::system::error_code & ec);
  » more...

Set the callback used to verify peer certificates.

template<
    typename VerifyCallback>
void set_verify_callback(
    VerifyCallback callback);

This function is used to specify a callback function that will be called by the implementation when it needs to verify a peer certificate.

Parameters

callback

The function object to be used for verifying a certificate. The function signature of the handler must be:

bool verify_callback(
  bool preverified, // True if the certificate passed pre-verification.
  verify_context& ctx // The peer certificate and other context.
);

The return value of the callback is true if the certificate has passed verification, false otherwise.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Calls SSL_set_verify.

Set the callback used to verify peer certificates.

template<
    typename VerifyCallback>
boost::system::error_code set_verify_callback(
    VerifyCallback callback,
    boost::system::error_code & ec);

This function is used to specify a callback function that will be called by the implementation when it needs to verify a peer certificate.

Parameters

callback

The function object to be used for verifying a certificate. The function signature of the handler must be:

bool verify_callback(
  bool preverified, // True if the certificate passed pre-verification.
  verify_context& ctx // The peer certificate and other context.
);

The return value of the callback is true if the certificate has passed verification, false otherwise.

ec

Set to indicate what error occurred, if any.

Remarks

Calls SSL_set_verify.

Set the peer verification depth.

void set_verify_depth(
    int depth);
  » more...

boost::system::error_code set_verify_depth(
    int depth,
    boost::system::error_code & ec);
  » more...

Set the peer verification depth.

void set_verify_depth(
    int depth);

This function may be used to configure the maximum verification depth allowed by the stream.

Parameters

depth

Maximum depth for the certificate chain verification that shall be allowed.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Calls SSL_set_verify_depth.

Set the peer verification depth.

boost::system::error_code set_verify_depth(
    int depth,
    boost::system::error_code & ec);

This function may be used to configure the maximum verification depth allowed by the stream.

Parameters

depth

Maximum depth for the certificate chain verification that shall be allowed.

ec

Set to indicate what error occurred, if any.

Remarks

Calls SSL_set_verify_depth.

Set the peer verification mode.

void set_verify_mode(
    verify_mode v);
  » more...

boost::system::error_code set_verify_mode(
    verify_mode v,
    boost::system::error_code & ec);
  » more...

Set the peer verification mode.

void set_verify_mode(
    verify_mode v);

This function may be used to configure the peer verification mode used by the stream. The new mode will override the mode inherited from the context.

Parameters

v

A bitmask of peer verification modes. See ssl::verify_mode for available values.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

Calls SSL_set_verify.

Set the peer verification mode.

boost::system::error_code set_verify_mode(
    verify_mode v,
    boost::system::error_code & ec);

This function may be used to configure the peer verification mode used by the stream. The new mode will override the mode inherited from the context.

Parameters

v

A bitmask of peer verification modes. See ssl::verify_mode for available values.

ec

Set to indicate what error occurred, if any.

Remarks

Calls SSL_set_verify.

Shut down SSL on the stream.

void shutdown();
  » more...

boost::system::error_code shutdown(
    boost::system::error_code & ec);
  » more...

Shut down SSL on the stream.

void shutdown();

This function is used to shut down SSL on the stream. The function call will block until SSL has been shut down or an error occurs.

Exceptions

boost::system::system_error

Thrown on failure.

Shut down SSL on the stream.

boost::system::error_code shutdown(
    boost::system::error_code & ec);

This function is used to shut down SSL on the stream. The function call will block until SSL has been shut down or an error occurs.

Parameters

ec

Set to indicate what error occurred, if any.

Construct a stream.

template<
    typename Arg>
stream(
    Arg & arg,
    context & ctx);

This constructor creates a stream and initialises the underlying stream object.

Parameters

arg

The argument to be passed to initialise the underlying stream.

ctx

The SSL context to be used for the stream.

Write some data to the stream.

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers);
  » more...

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers,
    boost::system::error_code & ec);
  » more...

Write some data to the stream.

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers);

This function is used to write data on the stream. The function call will block until one or more bytes of data has been written successfully, or until an error occurs.

Parameters

buffers

The data to be written.

Return Value

The number of bytes written.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

The write_some operation may not transmit all of the data to the peer. Consider using the write function if you need to ensure that all data is written before the blocking operation completes.

Write some data to the stream.

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers,
    boost::system::error_code & ec);

This function is used to write data on the stream. The function call will block until one or more bytes of data has been written successfully, or until an error occurs.

Parameters

buffers

The data to be written to the stream.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes written. Returns 0 if an error occurred.

Remarks

The write_some operation may not transmit all of the data to the peer. Consider using the write function if you need to ensure that all data is written before the blocking operation completes.

Destructor.

~stream();

Structure for use with deprecated impl_type.

struct impl_struct
Data Members

Name

Description

ssl

Requirements

Header: boost/asio/ssl/stream.hpp

Convenience header: boost/asio/ssl.hpp

The ssl::stream_base class is used as a base for the ssl::stream class template so that we have a common place to define various enums.

class stream_base
Types

Name

Description

handshake_type

Different handshake types.

Protected Member Functions

Name

Description

~stream_base

Protected destructor to prevent deletion through this type.

Requirements

Header: boost/asio/ssl/stream_base.hpp

Convenience header: boost/asio/ssl.hpp

Different handshake types.

enum handshake_type

Values

client

Perform handshaking as a client.

server

Perform handshaking as a server.

Protected destructor to prevent deletion through this type.

~stream_base();

Do not request client certificate on renegotiation. Ignored unless ssl::verify_peer is set.

const int verify_client_once = implementation_defined;
Requirements

Header: boost/asio/ssl/verify_mode.hpp

Convenience header: boost/asio/ssl.hpp

A simple wrapper around the X509_STORE_CTX type, used during verification of a peer certificate.

class verify_context :
  noncopyable
Types

Name

Description

native_handle_type

The native handle type of the verification context.

Member Functions

Name

Description

native_handle

Get the underlying implementation in the native type.

verify_context

Constructor.

Remarks

The ssl::verify_context does not own the underlying X509_STORE_CTX object.

Requirements

Header: boost/asio/ssl/verify_context.hpp

Convenience header: boost/asio/ssl.hpp

Get the underlying implementation in the native type.

native_handle_type native_handle();

This function may be used to obtain the underlying implementation of the context. This is intended to allow access to context functionality that is not otherwise provided.

The native handle type of the verification context.

typedef X509_STORE_CTX * native_handle_type;
Requirements

Header: boost/asio/ssl/verify_context.hpp

Convenience header: boost/asio/ssl.hpp

Constructor.

verify_context(
    native_handle_type handle);

Fail verification if the peer has no certificate. Ignored unless ssl::verify_peer is set.

const int verify_fail_if_no_peer_cert = implementation_defined;
Requirements

Header: boost/asio/ssl/verify_mode.hpp

Convenience header: boost/asio/ssl.hpp

Bitmask type for peer verification.

typedef int verify_mode;

Possible values are:

Requirements

Header: boost/asio/ssl/verify_mode.hpp

Convenience header: boost/asio/ssl.hpp

No verification.

const int verify_none = implementation_defined;
Requirements

Header: boost/asio/ssl/verify_mode.hpp

Convenience header: boost/asio/ssl.hpp

Verify the peer.

const int verify_peer = implementation_defined;
Requirements

Header: boost/asio/ssl/verify_mode.hpp

Convenience header: boost/asio/ssl.hpp

Typedef for a timer based on the steady clock.

typedef basic_waitable_timer< chrono::steady_clock > steady_timer;
Types

Name

Description

clock_type

The clock type.

duration

The duration type of the clock.

implementation_type

The underlying implementation type of I/O object.

service_type

The type of the service that will be used to provide I/O operations.

time_point

The time point type of the clock.

traits_type

The wait traits type.

Member Functions

Name

Description

async_wait

Start an asynchronous wait on the timer.

basic_waitable_timer

Constructor.

Constructor to set a particular expiry time as an absolute time.

Constructor to set a particular expiry time relative to now.

cancel

Cancel any asynchronous operations that are waiting on the timer.

cancel_one

Cancels one asynchronous operation that is waiting on the timer.

expires_at

Get the timer's expiry time as an absolute time.

Set the timer's expiry time as an absolute time.

expires_from_now

Get the timer's expiry time relative to now.

Set the timer's expiry time relative to now.

get_io_service

Get the io_service associated with the object.

wait

Perform a blocking wait on the timer.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_waitable_timer class template provides the ability to perform a blocking or asynchronous wait for a timer to expire.

A waitable timer is always in one of two states: "expired" or "not expired". If the wait() or async_wait() function is called on an expired timer, the wait operation will complete immediately.

Most applications will use one of the steady_timer, system_timer or high_resolution_timer typedefs.

Remarks

This waitable timer functionality is for use with the C++11 standard library's <chrono> facility, or with the Boost.Chrono library.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Examples

Performing a blocking wait (C++11):

// Construct a timer without setting an expiry time.
boost::asio::steady_timer timer(io_service);

// Set an expiry time relative to now.
timer.expires_from_now(std::chrono::seconds(5));

// Wait for the timer to expire.
timer.wait();

Performing an asynchronous wait (C++11):

void handler(const boost::system::error_code& error)
{
  if (!error)
  {
    // Timer expired.
  }
}

...

// Construct a timer with an absolute expiry time.
boost::asio::steady_timer timer(io_service,
    std::chrono::steady_clock::now() + std::chrono::seconds(60));

// Start an asynchronous wait.
timer.async_wait(handler);
Changing an active waitable timer's expiry time

Changing the expiry time of a timer while there are pending asynchronous waits causes those wait operations to be cancelled. To ensure that the action associated with the timer is performed only once, use something like this: used:

void on_some_event()
{
  if (my_timer.expires_from_now(seconds(5)) > 0)
  {
    // We managed to cancel the timer. Start new asynchronous wait.
    my_timer.async_wait(on_timeout);
  }
  else
  {
    // Too late, timer has already expired!
  }
}

void on_timeout(const boost::system::error_code& e)
{
  if (e != boost::asio::error::operation_aborted)
  {
    // Timer was not cancelled, take necessary action.
  }
}
  • The boost::asio::basic_waitable_timer::expires_from_now() function cancels any pending asynchronous waits, and returns the number of asynchronous waits that were cancelled. If it returns 0 then you were too late and the wait handler has already been executed, or will soon be executed. If it returns 1 then the wait handler was successfully cancelled.
  • If a wait handler is cancelled, the boost::system::error_code passed to it contains the value boost::asio::error::operation_aborted.

This typedef uses the C++11 <chrono> standard library facility, if available. Otherwise, it may use the Boost.Chrono library. To explicitly utilise Boost.Chrono, use the basic_waitable_timer template directly:

typedef basic_waitable_timer<boost::chrono::steady_clock> timer;
Requirements

Header: boost/asio/steady_timer.hpp

Convenience header: None

(Deprecated: Use io_service::strand.) Typedef for backwards compatibility.

typedef boost::asio::io_service::strand strand;
Member Functions

Name

Description

dispatch

Request the strand to invoke the given handler.

get_io_service

Get the io_service associated with the strand.

post

Request the strand to invoke the given handler and return immediately.

running_in_this_thread

Determine whether the strand is running in the current thread.

strand

Constructor.

wrap

Create a new handler that automatically dispatches the wrapped handler on the strand.

~strand

Destructor.

The io_service::strand class provides the ability to post and dispatch handlers with the guarantee that none of those handlers will execute concurrently.

Order of handler invocation

Given:

  • a strand object s
  • an object a meeting completion handler requirements
  • an object a1 which is an arbitrary copy of a made by the implementation
  • an object b meeting completion handler requirements
  • an object b1 which is an arbitrary copy of b made by the implementation

if any of the following conditions are true:

  • s.post(a) happens-before s.post(b)
  • s.post(a) happens-before s.dispatch(b), where the latter is performed outside the strand
  • s.dispatch(a) happens-before s.post(b), where the former is performed outside the strand
  • s.dispatch(a) happens-before s.dispatch(b), where both are performed outside the strand

then asio_handler_invoke(a1, &a1) happens-before asio_handler_invoke(b1, &b1).

Note that in the following case:

async_op_1(..., s.wrap(a));
async_op_2(..., s.wrap(b));

the completion of the first async operation will perform s.dispatch(a), and the second will perform s.dispatch(b), but the order in which those are performed is unspecified. That is, you cannot state whether one happens-before the other. Therefore none of the above conditions are met and no ordering guarantee is made.

Remarks

The implementation makes no guarantee that handlers posted or dispatched through different strand objects will be invoked concurrently.

Thread Safety

Distinct objects: Safe.

Shared objects: Safe.

Requirements

Header: boost/asio/strand.hpp

Convenience header: boost/asio.hpp

Default service implementation for a stream socket.

template<
    typename Protocol>
class stream_socket_service :
  public io_service::service
Types

Name

Description

endpoint_type

The endpoint type.

implementation_type

The type of a stream socket implementation.

native_handle_type

The native socket type.

native_type

(Deprecated: Use native_handle_type.) The native socket type.

protocol_type

The protocol type.

Member Functions

Name

Description

assign

Assign an existing native socket to a stream socket.

async_connect

Start an asynchronous connect.

async_receive

Start an asynchronous receive.

async_send

Start an asynchronous send.

at_mark

Determine whether the socket is at the out-of-band data mark.

available

Determine the number of bytes available for reading.

bind

Bind the stream socket to the specified local endpoint.

cancel

Cancel all asynchronous operations associated with the socket.

close

Close a stream socket implementation.

connect

Connect the stream socket to the specified endpoint.

construct

Construct a new stream socket implementation.

converting_move_construct

Move-construct a new stream socket implementation from another protocol type.

destroy

Destroy a stream socket implementation.

get_io_service

Get the io_service object that owns the service.

get_option

Get a socket option.

io_control

Perform an IO control command on the socket.

is_open

Determine whether the socket is open.

local_endpoint

Get the local endpoint.

move_assign

Move-assign from another stream socket implementation.

move_construct

Move-construct a new stream socket implementation.

native

(Deprecated: Use native_handle().) Get the native socket implementation.

native_handle

Get the native socket implementation.

native_non_blocking

Gets the non-blocking mode of the native socket implementation.

Sets the non-blocking mode of the native socket implementation.

non_blocking

Gets the non-blocking mode of the socket.

Sets the non-blocking mode of the socket.

open

Open a stream socket.

receive

Receive some data from the peer.

remote_endpoint

Get the remote endpoint.

send

Send the given data to the peer.

set_option

Set a socket option.

shutdown

Disable sends or receives on the socket.

stream_socket_service

Construct a new stream socket service for the specified io_service.

Data Members

Name

Description

id

The unique service identifier.

Requirements

Header: boost/asio/stream_socket_service.hpp

Convenience header: boost/asio.hpp

Assign an existing native socket to a stream socket.

boost::system::error_code assign(
    implementation_type & impl,
    const protocol_type & protocol,
    const native_handle_type & native_socket,
    boost::system::error_code & ec);

Start an asynchronous connect.

template<
    typename ConnectHandler>
void-or-deduced async_connect(
    implementation_type & impl,
    const endpoint_type & peer_endpoint,
    ConnectHandler handler);

Start an asynchronous receive.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_receive(
    implementation_type & impl,
    const MutableBufferSequence & buffers,
    socket_base::message_flags flags,
    ReadHandler handler);

Start an asynchronous send.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_send(
    implementation_type & impl,
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags,
    WriteHandler handler);

Determine whether the socket is at the out-of-band data mark.

bool at_mark(
    const implementation_type & impl,
    boost::system::error_code & ec) const;

Determine the number of bytes available for reading.

std::size_t available(
    const implementation_type & impl,
    boost::system::error_code & ec) const;

Bind the stream socket to the specified local endpoint.

boost::system::error_code bind(
    implementation_type & impl,
    const endpoint_type & endpoint,
    boost::system::error_code & ec);

Cancel all asynchronous operations associated with the socket.

boost::system::error_code cancel(
    implementation_type & impl,
    boost::system::error_code & ec);

Close a stream socket implementation.

boost::system::error_code close(
    implementation_type & impl,
    boost::system::error_code & ec);

Connect the stream socket to the specified endpoint.

boost::system::error_code connect(
    implementation_type & impl,
    const endpoint_type & peer_endpoint,
    boost::system::error_code & ec);

Construct a new stream socket implementation.

void construct(
    implementation_type & impl);

Move-construct a new stream socket implementation from another protocol type.

template<
    typename Protocol1>
void converting_move_construct(
    implementation_type & impl,
    typename stream_socket_service< Protocol1 >::implementation_type & other_impl,
    typename enable_if< is_convertible< Protocol1, Protocol >::value >::type *  = 0);

Destroy a stream socket implementation.

void destroy(
    implementation_type & impl);

The endpoint type.

typedef Protocol::endpoint endpoint_type;
Requirements

Header: boost/asio/stream_socket_service.hpp

Convenience header: boost/asio.hpp

Inherited from io_service.

Get the io_service object that owns the service.

boost::asio::io_service & get_io_service();

Get a socket option.

template<
    typename GettableSocketOption>
boost::system::error_code get_option(
    const implementation_type & impl,
    GettableSocketOption & option,
    boost::system::error_code & ec) const;

The unique service identifier.

static boost::asio::io_service::id id;

The type of a stream socket implementation.

typedef implementation_defined implementation_type;
Requirements

Header: boost/asio/stream_socket_service.hpp

Convenience header: boost/asio.hpp

Perform an IO control command on the socket.

template<
    typename IoControlCommand>
boost::system::error_code io_control(
    implementation_type & impl,
    IoControlCommand & command,
    boost::system::error_code & ec);

Determine whether the socket is open.

bool is_open(
    const implementation_type & impl) const;

Get the local endpoint.

endpoint_type local_endpoint(
    const implementation_type & impl,
    boost::system::error_code & ec) const;

Move-assign from another stream socket implementation.

void move_assign(
    implementation_type & impl,
    stream_socket_service & other_service,
    implementation_type & other_impl);

Move-construct a new stream socket implementation.

void move_construct(
    implementation_type & impl,
    implementation_type & other_impl);

(Deprecated: Use native_handle().) Get the native socket implementation.

native_type native(
    implementation_type & impl);

Get the native socket implementation.

native_handle_type native_handle(
    implementation_type & impl);

The native socket type.

typedef implementation_defined native_handle_type;
Requirements

Header: boost/asio/stream_socket_service.hpp

Convenience header: boost/asio.hpp

Gets the non-blocking mode of the native socket implementation.

bool native_non_blocking(
    const implementation_type & impl) const;
  » more...

Sets the non-blocking mode of the native socket implementation.

boost::system::error_code native_non_blocking(
    implementation_type & impl,
    bool mode,
    boost::system::error_code & ec);
  » more...

Gets the non-blocking mode of the native socket implementation.

bool native_non_blocking(
    const implementation_type & impl) const;

Sets the non-blocking mode of the native socket implementation.

boost::system::error_code native_non_blocking(
    implementation_type & impl,
    bool mode,
    boost::system::error_code & ec);

(Deprecated: Use native_handle_type.) The native socket type.

typedef implementation_defined native_type;
Requirements

Header: boost/asio/stream_socket_service.hpp

Convenience header: boost/asio.hpp

Gets the non-blocking mode of the socket.

bool non_blocking(
    const implementation_type & impl) const;
  » more...

Sets the non-blocking mode of the socket.

boost::system::error_code non_blocking(
    implementation_type & impl,
    bool mode,
    boost::system::error_code & ec);
  » more...

Gets the non-blocking mode of the socket.

bool non_blocking(
    const implementation_type & impl) const;

Sets the non-blocking mode of the socket.

boost::system::error_code non_blocking(
    implementation_type & impl,
    bool mode,
    boost::system::error_code & ec);

Open a stream socket.

boost::system::error_code open(
    implementation_type & impl,
    const protocol_type & protocol,
    boost::system::error_code & ec);

The protocol type.

typedef Protocol protocol_type;
Requirements

Header: boost/asio/stream_socket_service.hpp

Convenience header: boost/asio.hpp

Receive some data from the peer.

template<
    typename MutableBufferSequence>
std::size_t receive(
    implementation_type & impl,
    const MutableBufferSequence & buffers,
    socket_base::message_flags flags,
    boost::system::error_code & ec);

Get the remote endpoint.

endpoint_type remote_endpoint(
    const implementation_type & impl,
    boost::system::error_code & ec) const;

Send the given data to the peer.

template<
    typename ConstBufferSequence>
std::size_t send(
    implementation_type & impl,
    const ConstBufferSequence & buffers,
    socket_base::message_flags flags,
    boost::system::error_code & ec);

Set a socket option.

template<
    typename SettableSocketOption>
boost::system::error_code set_option(
    implementation_type & impl,
    const SettableSocketOption & option,
    boost::system::error_code & ec);

Disable sends or receives on the socket.

boost::system::error_code shutdown(
    implementation_type & impl,
    socket_base::shutdown_type what,
    boost::system::error_code & ec);

Construct a new stream socket service for the specified io_service.

stream_socket_service(
    boost::asio::io_service & io_service);

Typedef for the typical usage of basic_streambuf.

typedef basic_streambuf streambuf;
Types

Name

Description

const_buffers_type

The type used to represent the input sequence as a list of buffers.

mutable_buffers_type

The type used to represent the output sequence as a list of buffers.

Member Functions

Name

Description

basic_streambuf

Construct a basic_streambuf object.

commit

Move characters from the output sequence to the input sequence.

consume

Remove characters from the input sequence.

data

Get a list of buffers that represents the input sequence.

max_size

Get the maximum size of the basic_streambuf.

prepare

Get a list of buffers that represents the output sequence, with the given size.

size

Get the size of the input sequence.

Protected Member Functions

Name

Description

overflow

Override std::streambuf behaviour.

reserve

underflow

Override std::streambuf behaviour.

The basic_streambuf class is derived from std::streambuf to associate the streambuf's input and output sequences with one or more character arrays. These character arrays are internal to the basic_streambuf object, but direct access to the array elements is provided to permit them to be used efficiently with I/O operations. Characters written to the output sequence of a basic_streambuf object are appended to the input sequence of the same object.

The basic_streambuf class's public interface is intended to permit the following implementation strategies:

  • A single contiguous character array, which is reallocated as necessary to accommodate changes in the size of the character sequence. This is the implementation approach currently used in Asio.
  • A sequence of one or more character arrays, where each array is of the same size. Additional character array objects are appended to the sequence to accommodate changes in the size of the character sequence.
  • A sequence of one or more character arrays of varying sizes. Additional character array objects are appended to the sequence to accommodate changes in the size of the character sequence.

The constructor for basic_streambuf accepts a size_t argument specifying the maximum of the sum of the sizes of the input sequence and output sequence. During the lifetime of the basic_streambuf object, the following invariant holds:

size() <= max_size()

Any member function that would, if successful, cause the invariant to be violated shall throw an exception of class std::length_error.

The constructor for basic_streambuf takes an Allocator argument. A copy of this argument is used for any memory allocation performed, by the constructor and by all member functions, during the lifetime of each basic_streambuf object.

Examples

Writing directly from an streambuf to a socket:

boost::asio::streambuf b;
std::ostream os(&b);
os << "Hello, World!\n";

// try sending some data in input sequence
size_t n = sock.send(b.data());

b.consume(n); // sent data is removed from input sequence

Reading from a socket directly into a streambuf:

boost::asio::streambuf b;

// reserve 512 bytes in output sequence
boost::asio::streambuf::mutable_buffers_type bufs = b.prepare(512);

size_t n = sock.receive(bufs);

// received data is "committed" from output sequence to input sequence
b.commit(n);

std::istream is(&b);
std::string s;
is >> s;
Requirements

Header: boost/asio/streambuf.hpp

Convenience header: boost/asio.hpp

Typedef for a timer based on the system clock.

typedef basic_waitable_timer< chrono::system_clock > system_timer;
Types

Name

Description

clock_type

The clock type.

duration

The duration type of the clock.

implementation_type

The underlying implementation type of I/O object.

service_type

The type of the service that will be used to provide I/O operations.

time_point

The time point type of the clock.

traits_type

The wait traits type.

Member Functions

Name

Description

async_wait

Start an asynchronous wait on the timer.

basic_waitable_timer

Constructor.

Constructor to set a particular expiry time as an absolute time.

Constructor to set a particular expiry time relative to now.

cancel

Cancel any asynchronous operations that are waiting on the timer.

cancel_one

Cancels one asynchronous operation that is waiting on the timer.

expires_at

Get the timer's expiry time as an absolute time.

Set the timer's expiry time as an absolute time.

expires_from_now

Get the timer's expiry time relative to now.

Set the timer's expiry time relative to now.

get_io_service

Get the io_service associated with the object.

wait

Perform a blocking wait on the timer.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The basic_waitable_timer class template provides the ability to perform a blocking or asynchronous wait for a timer to expire.

A waitable timer is always in one of two states: "expired" or "not expired". If the wait() or async_wait() function is called on an expired timer, the wait operation will complete immediately.

Most applications will use one of the steady_timer, system_timer or high_resolution_timer typedefs.

Remarks

This waitable timer functionality is for use with the C++11 standard library's <chrono> facility, or with the Boost.Chrono library.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Examples

Performing a blocking wait (C++11):

// Construct a timer without setting an expiry time.
boost::asio::steady_timer timer(io_service);

// Set an expiry time relative to now.
timer.expires_from_now(std::chrono::seconds(5));

// Wait for the timer to expire.
timer.wait();

Performing an asynchronous wait (C++11):

void handler(const boost::system::error_code& error)
{
  if (!error)
  {
    // Timer expired.
  }
}

...

// Construct a timer with an absolute expiry time.
boost::asio::steady_timer timer(io_service,
    std::chrono::steady_clock::now() + std::chrono::seconds(60));

// Start an asynchronous wait.
timer.async_wait(handler);
Changing an active waitable timer's expiry time

Changing the expiry time of a timer while there are pending asynchronous waits causes those wait operations to be cancelled. To ensure that the action associated with the timer is performed only once, use something like this: used:

void on_some_event()
{
  if (my_timer.expires_from_now(seconds(5)) > 0)
  {
    // We managed to cancel the timer. Start new asynchronous wait.
    my_timer.async_wait(on_timeout);
  }
  else
  {
    // Too late, timer has already expired!
  }
}

void on_timeout(const boost::system::error_code& e)
{
  if (e != boost::asio::error::operation_aborted)
  {
    // Timer was not cancelled, take necessary action.
  }
}
  • The boost::asio::basic_waitable_timer::expires_from_now() function cancels any pending asynchronous waits, and returns the number of asynchronous waits that were cancelled. If it returns 0 then you were too late and the wait handler has already been executed, or will soon be executed. If it returns 1 then the wait handler was successfully cancelled.
  • If a wait handler is cancelled, the boost::system::error_code passed to it contains the value boost::asio::error::operation_aborted.

This typedef uses the C++11 <chrono> standard library facility, if available. Otherwise, it may use the Boost.Chrono library. To explicitly utilise Boost.Chrono, use the basic_waitable_timer template directly:

typedef basic_waitable_timer<boost::chrono::system_clock> timer;
Requirements

Header: boost/asio/system_timer.hpp

Convenience header: None

Time traits specialised for posix_time.

template<>
struct time_traits< boost::posix_time::ptime >
Types

Name

Description

duration_type

The duration type.

time_type

The time type.

Member Functions

Name

Description

add

Add a duration to a time.

less_than

Test whether one time is less than another.

now

Get the current time.

subtract

Subtract one time from another.

to_posix_duration

Convert to POSIX duration type.

Requirements

Header: boost/asio/time_traits.hpp

Convenience header: boost/asio.hpp

Add a duration to a time.

static time_type add(
    const time_type & t,
    const duration_type & d);

The duration type.

typedef boost::posix_time::time_duration duration_type;
Requirements

Header: boost/asio/time_traits.hpp

Convenience header: boost/asio.hpp

Test whether one time is less than another.

static bool less_than(
    const time_type & t1,
    const time_type & t2);

Get the current time.

static time_type now();

Subtract one time from another.

static duration_type subtract(
    const time_type & t1,
    const time_type & t2);

The time type.

typedef boost::posix_time::ptime time_type;
Requirements

Header: boost/asio/time_traits.hpp

Convenience header: boost/asio.hpp

Convert to POSIX duration type.

static boost::posix_time::time_duration to_posix_duration(
    const duration_type & d);

Return a completion condition function object that indicates that a read or write operation should continue until all of the data has been transferred, or until an error occurs.

unspecified transfer_all();

This function is used to create an object, of unspecified type, that meets CompletionCondition requirements.

Example

Reading until a buffer is full:

boost::array<char, 128> buf;
boost::system::error_code ec;
std::size_t n = boost::asio::read(
    sock, boost::asio::buffer(buf),
    boost::asio::transfer_all(), ec);
if (ec)
{
  // An error occurred.
}
else
{
  // n == 128
}
Requirements

Header: boost/asio/completion_condition.hpp

Convenience header: boost/asio.hpp

Return a completion condition function object that indicates that a read or write operation should continue until a minimum number of bytes has been transferred, or until an error occurs.

unspecified transfer_at_least(
    std::size_t minimum);

This function is used to create an object, of unspecified type, that meets CompletionCondition requirements.

Example

Reading until a buffer is full or contains at least 64 bytes:

boost::array<char, 128> buf;
boost::system::error_code ec;
std::size_t n = boost::asio::read(
    sock, boost::asio::buffer(buf),
    boost::asio::transfer_at_least(64), ec);
if (ec)
{
  // An error occurred.
}
else
{
  // n >= 64 && n <= 128
}
Requirements

Header: boost/asio/completion_condition.hpp

Convenience header: boost/asio.hpp

Return a completion condition function object that indicates that a read or write operation should continue until an exact number of bytes has been transferred, or until an error occurs.

unspecified transfer_exactly(
    std::size_t size);

This function is used to create an object, of unspecified type, that meets CompletionCondition requirements.

Example

Reading until a buffer is full or contains exactly 64 bytes:

boost::array<char, 128> buf;
boost::system::error_code ec;
std::size_t n = boost::asio::read(
    sock, boost::asio::buffer(buf),
    boost::asio::transfer_exactly(64), ec);
if (ec)
{
  // An error occurred.
}
else
{
  // n == 64
}
Requirements

Header: boost/asio/completion_condition.hpp

Convenience header: boost/asio.hpp

A special value, similar to std::nothrow.

constexpr use_future_t use_future;

See the documentation for use_future_t for a usage example.

Requirements

Header: boost/asio/use_future.hpp

Convenience header: None

Class used to specify that an asynchronous operation should return a future.

template<
    typename Allocator = std::allocator<void>>
class use_future_t
Types

Name

Description

allocator_type

The allocator type. The allocator is used when constructing the std::promise object for a given asynchronous operation.

Member Functions

Name

Description

get_allocator

Obtain allocator.

operator[]

Specify an alternate allocator.

use_future_t

Construct using default-constructed allocator.

Construct using specified allocator.

The use_future_t class is used to indicate that an asynchronous operation should return a std::future object. A use_future_t object may be passed as a handler to an asynchronous operation, typically using the special value boost::asio::use_future. For example:

std::future<std::size_t> my_future
  = my_socket.async_read_some(my_buffer, boost::asio::use_future);

The initiating function (async_read_some in the above example) returns a future that will receive the result of the operation. If the operation completes with an error_code indicating failure, it is converted into a system_error and passed back to the caller via the future.

Requirements

Header: boost/asio/use_future.hpp

Convenience header: None

The allocator type. The allocator is used when constructing the std::promise object for a given asynchronous operation.

typedef Allocator allocator_type;
Requirements

Header: boost/asio/use_future.hpp

Convenience header: None

Obtain allocator.

allocator_type get_allocator() const;

Specify an alternate allocator.

template<
    typename OtherAllocator>
use_future_t< OtherAllocator > operator[](
    const OtherAllocator & allocator) const;

Construct using default-constructed allocator.

constexpr use_future_t();
  » more...

Construct using specified allocator.

explicit use_future_t(
    const Allocator & allocator);
  » more...

Construct using default-constructed allocator.

constexpr use_future_t();

Construct using specified allocator.

use_future_t(
    const Allocator & allocator);

template<
    typename Service>
Service & use_service(
    io_service & ios);

This function is used to locate a service object that corresponds to the given service type. If there is no existing implementation of the service, then the io_service will create a new instance of the service.

Parameters

ios

The io_service object that owns the service.

Return Value

The service interface implementing the specified service type. Ownership of the service interface is not transferred to the caller.

Requirements

Header: boost/asio/io_service.hpp

Convenience header: boost/asio.hpp

Wait traits suitable for use with the basic_waitable_timer class template.

template<
    typename Clock>
struct wait_traits
Member Functions

Name

Description

to_wait_duration

Convert a clock duration into a duration used for waiting.

Requirements

Header: boost/asio/wait_traits.hpp

Convenience header: boost/asio.hpp

Convert a clock duration into a duration used for waiting.

static Clock::duration to_wait_duration(
    const typename Clock::duration & d);
Return Value

d.

Default service implementation for a timer.

template<
    typename Clock,
    typename WaitTraits = boost::asio::wait_traits<Clock>>
class waitable_timer_service :
  public io_service::service
Types

Name

Description

clock_type

The clock type.

duration

The duration type of the clock.

implementation_type

The implementation type of the waitable timer.

time_point

The time point type of the clock.

traits_type

The wait traits type.

Member Functions

Name

Description

async_wait

cancel

Cancel any asynchronous wait operations associated with the timer.

cancel_one

Cancels one asynchronous wait operation associated with the timer.

construct

Construct a new timer implementation.

destroy

Destroy a timer implementation.

expires_at

Get the expiry time for the timer as an absolute time.

Set the expiry time for the timer as an absolute time.

expires_from_now

Get the expiry time for the timer relative to now.

Set the expiry time for the timer relative to now.

get_io_service

Get the io_service object that owns the service.

wait

waitable_timer_service

Construct a new timer service for the specified io_service.

Data Members

Name

Description

id

The unique service identifier.

Requirements

Header: boost/asio/waitable_timer_service.hpp

Convenience header: boost/asio.hpp

template<
    typename WaitHandler>
void-or-deduced async_wait(
    implementation_type & impl,
    WaitHandler handler);

Cancel any asynchronous wait operations associated with the timer.

std::size_t cancel(
    implementation_type & impl,
    boost::system::error_code & ec);

Cancels one asynchronous wait operation associated with the timer.

std::size_t cancel_one(
    implementation_type & impl,
    boost::system::error_code & ec);

The clock type.

typedef Clock clock_type;
Requirements

Header: boost/asio/waitable_timer_service.hpp

Convenience header: boost/asio.hpp

Construct a new timer implementation.

void construct(
    implementation_type & impl);

Destroy a timer implementation.

void destroy(
    implementation_type & impl);

The duration type of the clock.

typedef clock_type::duration duration;
Requirements

Header: boost/asio/waitable_timer_service.hpp

Convenience header: boost/asio.hpp

Get the expiry time for the timer as an absolute time.

time_point expires_at(
    const implementation_type & impl) const;
  » more...

Set the expiry time for the timer as an absolute time.

std::size_t expires_at(
    implementation_type & impl,
    const time_point & expiry_time,
    boost::system::error_code & ec);
  » more...

Get the expiry time for the timer as an absolute time.

time_point expires_at(
    const implementation_type & impl) const;

Set the expiry time for the timer as an absolute time.

std::size_t expires_at(
    implementation_type & impl,
    const time_point & expiry_time,
    boost::system::error_code & ec);

Get the expiry time for the timer relative to now.

duration expires_from_now(
    const implementation_type & impl) const;
  » more...

Set the expiry time for the timer relative to now.

std::size_t expires_from_now(
    implementation_type & impl,
    const duration & expiry_time,
    boost::system::error_code & ec);
  » more...

Get the expiry time for the timer relative to now.

duration expires_from_now(
    const implementation_type & impl) const;

Set the expiry time for the timer relative to now.

std::size_t expires_from_now(
    implementation_type & impl,
    const duration & expiry_time,
    boost::system::error_code & ec);

Inherited from io_service.

Get the io_service object that owns the service.

boost::asio::io_service & get_io_service();

The unique service identifier.

static boost::asio::io_service::id id;

The implementation type of the waitable timer.

typedef implementation_defined implementation_type;
Requirements

Header: boost/asio/waitable_timer_service.hpp

Convenience header: boost/asio.hpp

The time point type of the clock.

typedef clock_type::time_point time_point;
Requirements

Header: boost/asio/waitable_timer_service.hpp

Convenience header: boost/asio.hpp

The wait traits type.

typedef WaitTraits traits_type;
Requirements

Header: boost/asio/waitable_timer_service.hpp

Convenience header: boost/asio.hpp

void wait(
    implementation_type & impl,
    boost::system::error_code & ec);

Construct a new timer service for the specified io_service.

waitable_timer_service(
    boost::asio::io_service & io_service);

Provides Windows handle functionality.

template<
    typename HandleService>
class basic_handle :
  public basic_io_object< HandleService >
Types

Name

Description

implementation_type

The underlying implementation type of I/O object.

lowest_layer_type

A basic_handle is always the lowest layer.

native_handle_type

The native representation of a handle.

native_type

(Deprecated: Use native_handle_type.) The native representation of a handle.

service_type

The type of the service that will be used to provide I/O operations.

Member Functions

Name

Description

assign

Assign an existing native handle to the handle.

basic_handle

Construct a basic_handle without opening it.

Construct a basic_handle on an existing native handle.

Move-construct a basic_handle from another.

cancel

Cancel all asynchronous operations associated with the handle.

close

Close the handle.

get_io_service

Get the io_service associated with the object.

is_open

Determine whether the handle is open.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native handle representation.

native_handle

Get the native handle representation.

operator=

Move-assign a basic_handle from another.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

~basic_handle

Protected destructor to prevent deletion through this type.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The windows::basic_handle class template provides the ability to wrap a Windows handle.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/windows/basic_handle.hpp

Convenience header: boost/asio.hpp

Assign an existing native handle to the handle.

void assign(
    const native_handle_type & handle);
  » more...

boost::system::error_code assign(
    const native_handle_type & handle,
    boost::system::error_code & ec);
  » more...

Assign an existing native handle to the handle.

void assign(
    const native_handle_type & handle);

Assign an existing native handle to the handle.

boost::system::error_code assign(
    const native_handle_type & handle,
    boost::system::error_code & ec);

Construct a windows::basic_handle without opening it.

explicit basic_handle(
    boost::asio::io_service & io_service);
  » more...

Construct a windows::basic_handle on an existing native handle.

basic_handle(
    boost::asio::io_service & io_service,
    const native_handle_type & handle);
  » more...

Move-construct a windows::basic_handle from another.

basic_handle(
    basic_handle && other);
  » more...

Construct a windows::basic_handle without opening it.

basic_handle(
    boost::asio::io_service & io_service);

This constructor creates a handle without opening it.

Parameters

io_service

The io_service object that the handle will use to dispatch handlers for any asynchronous operations performed on the handle.

Construct a windows::basic_handle on an existing native handle.

basic_handle(
    boost::asio::io_service & io_service,
    const native_handle_type & handle);

This constructor creates a handle object to hold an existing native handle.

Parameters

io_service

The io_service object that the handle will use to dispatch handlers for any asynchronous operations performed on the handle.

handle

A native handle.

Exceptions

boost::system::system_error

Thrown on failure.

Move-construct a windows::basic_handle from another.

basic_handle(
    basic_handle && other);

This constructor moves a handle from one object to another.

Parameters

other

The other windows::basic_handle object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_handle(io_service&) constructor.

Cancel all asynchronous operations associated with the handle.

void cancel();
  » more...

boost::system::error_code cancel(
    boost::system::error_code & ec);
  » more...

Cancel all asynchronous operations associated with the handle.

void cancel();

This function causes all outstanding asynchronous read or write operations to finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error.

Exceptions

boost::system::system_error

Thrown on failure.

Cancel all asynchronous operations associated with the handle.

boost::system::error_code cancel(
    boost::system::error_code & ec);

This function causes all outstanding asynchronous read or write operations to finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error.

Parameters

ec

Set to indicate what error occurred, if any.

Close the handle.

void close();
  » more...

boost::system::error_code close(
    boost::system::error_code & ec);
  » more...

Close the handle.

void close();

This function is used to close the handle. Any asynchronous read or write operations will be cancelled immediately, and will complete with the boost::asio::error::operation_aborted error.

Exceptions

boost::system::system_error

Thrown on failure.

Close the handle.

boost::system::error_code close(
    boost::system::error_code & ec);

This function is used to close the handle. Any asynchronous read or write operations will be cancelled immediately, and will complete with the boost::asio::error::operation_aborted error.

Parameters

ec

Set to indicate what error occurred, if any.

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();
  » more...

const implementation_type & get_implementation() const;
  » more...

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

const implementation_type & get_implementation() const;

Inherited from basic_io_object.

Get the io_service associated with the object.

boost::asio::io_service & get_io_service();

This function may be used to obtain the io_service object that the I/O object uses to dispatch handlers for asynchronous operations.

Return Value

A reference to the io_service object that the I/O object will use to dispatch handlers. Ownership is not transferred to the caller.

Get the service associated with the I/O object.

service_type & get_service();
  » more...

const service_type & get_service() const;
  » more...

Inherited from basic_io_object.

Get the service associated with the I/O object.

service_type & get_service();

Inherited from basic_io_object.

Get the service associated with the I/O object.

const service_type & get_service() const;

Inherited from basic_io_object.

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

implementation_type implementation;

Inherited from basic_io_object.

The underlying implementation type of I/O object.

typedef service_type::implementation_type implementation_type;
Requirements

Header: boost/asio/windows/basic_handle.hpp

Convenience header: boost/asio.hpp

Determine whether the handle is open.

bool is_open() const;

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();
  » more...

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;
  » more...

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();

This function returns a reference to the lowest layer in a stack of layers. Since a windows::basic_handle cannot contain any further layers, it simply returns a reference to itself.

Return Value

A reference to the lowest layer in the stack of layers. Ownership is not transferred to the caller.

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;

This function returns a const reference to the lowest layer in a stack of layers. Since a windows::basic_handle cannot contain any further layers, it simply returns a reference to itself.

Return Value

A const reference to the lowest layer in the stack of layers. Ownership is not transferred to the caller.

A windows::basic_handle is always the lowest layer.

typedef basic_handle< HandleService > lowest_layer_type;
Types

Name

Description

implementation_type

The underlying implementation type of I/O object.

lowest_layer_type

A basic_handle is always the lowest layer.

native_handle_type

The native representation of a handle.

native_type

(Deprecated: Use native_handle_type.) The native representation of a handle.

service_type

The type of the service that will be used to provide I/O operations.

Member Functions

Name

Description

assign

Assign an existing native handle to the handle.

basic_handle

Construct a basic_handle without opening it.

Construct a basic_handle on an existing native handle.

Move-construct a basic_handle from another.

cancel

Cancel all asynchronous operations associated with the handle.

close

Close the handle.

get_io_service

Get the io_service associated with the object.

is_open

Determine whether the handle is open.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native handle representation.

native_handle

Get the native handle representation.

operator=

Move-assign a basic_handle from another.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

~basic_handle

Protected destructor to prevent deletion through this type.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The windows::basic_handle class template provides the ability to wrap a Windows handle.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/windows/basic_handle.hpp

Convenience header: boost/asio.hpp

(Deprecated: Use native_handle().) Get the native handle representation.

native_type native();

This function may be used to obtain the underlying representation of the handle. This is intended to allow access to native handle functionality that is not otherwise provided.

Get the native handle representation.

native_handle_type native_handle();

This function may be used to obtain the underlying representation of the handle. This is intended to allow access to native handle functionality that is not otherwise provided.

The native representation of a handle.

typedef HandleService::native_handle_type native_handle_type;
Requirements

Header: boost/asio/windows/basic_handle.hpp

Convenience header: boost/asio.hpp

(Deprecated: Use native_handle_type.) The native representation of a handle.

typedef HandleService::native_handle_type native_type;
Requirements

Header: boost/asio/windows/basic_handle.hpp

Convenience header: boost/asio.hpp

Move-assign a windows::basic_handle from another.

basic_handle & operator=(
    basic_handle && other);

This assignment operator moves a handle from one object to another.

Parameters

other

The other windows::basic_handle object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_handle(io_service&) constructor.

Inherited from basic_io_object.

(Deprecated: Use get_service().) The service associated with the I/O object.

service_type & service;
Remarks

Available only for services that do not support movability.

Inherited from basic_io_object.

The type of the service that will be used to provide I/O operations.

typedef HandleService service_type;
Requirements

Header: boost/asio/windows/basic_handle.hpp

Convenience header: boost/asio.hpp

Protected destructor to prevent deletion through this type.

~basic_handle();

Provides object-oriented handle functionality.

template<
    typename ObjectHandleService = object_handle_service>
class basic_object_handle :
  public windows::basic_handle< ObjectHandleService >
Types

Name

Description

implementation_type

The underlying implementation type of I/O object.

lowest_layer_type

A basic_handle is always the lowest layer.

native_handle_type

The native representation of a handle.

native_type

(Deprecated: Use native_handle_type.) The native representation of a handle.

service_type

The type of the service that will be used to provide I/O operations.

Member Functions

Name

Description

assign

Assign an existing native handle to the handle.

async_wait

Start an asynchronous wait on the object handle.

basic_object_handle

Construct a basic_object_handle without opening it.

Construct a basic_object_handle on an existing native handle.

Move-construct a basic_object_handle from another.

cancel

Cancel all asynchronous operations associated with the handle.

close

Close the handle.

get_io_service

Get the io_service associated with the object.

is_open

Determine whether the handle is open.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native handle representation.

native_handle

Get the native handle representation.

operator=

Move-assign a basic_object_handle from another.

wait

Perform a blocking wait on the object handle.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The windows::basic_object_handle class template provides asynchronous and blocking object-oriented handle functionality.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/windows/basic_object_handle.hpp

Convenience header: boost/asio.hpp

Assign an existing native handle to the handle.

void assign(
    const native_handle_type & handle);
  » more...

boost::system::error_code assign(
    const native_handle_type & handle,
    boost::system::error_code & ec);
  » more...

Inherited from windows::basic_handle.

Assign an existing native handle to the handle.

void assign(
    const native_handle_type & handle);

Inherited from windows::basic_handle.

Assign an existing native handle to the handle.

boost::system::error_code assign(
    const native_handle_type & handle,
    boost::system::error_code & ec);

Start an asynchronous wait on the object handle.

template<
    typename WaitHandler>
void-or-deduced async_wait(
    WaitHandler handler);

This function is be used to initiate an asynchronous wait against the object handle. It always returns immediately.

Parameters

handler

The handler to be called when the object handle is set to the signalled state. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error // Result of operation.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Construct a windows::basic_object_handle without opening it.

explicit basic_object_handle(
    boost::asio::io_service & io_service);
  » more...

Construct a windows::basic_object_handle on an existing native handle.

basic_object_handle(
    boost::asio::io_service & io_service,
    const native_handle_type & native_handle);
  » more...

Move-construct a windows::basic_object_handle from another.

basic_object_handle(
    basic_object_handle && other);
  » more...

Construct a windows::basic_object_handle without opening it.

basic_object_handle(
    boost::asio::io_service & io_service);

This constructor creates an object handle without opening it.

Parameters

io_service

The io_service object that the object handle will use to dispatch handlers for any asynchronous operations performed on the handle.

Construct a windows::basic_object_handle on an existing native handle.

basic_object_handle(
    boost::asio::io_service & io_service,
    const native_handle_type & native_handle);

This constructor creates an object handle object to hold an existing native handle.

Parameters

io_service

The io_service object that the object handle will use to dispatch handlers for any asynchronous operations performed on the handle.

native_handle

The new underlying handle implementation.

Exceptions

boost::system::system_error

Thrown on failure.

Move-construct a windows::basic_object_handle from another.

basic_object_handle(
    basic_object_handle && other);

This constructor moves an object handle from one object to another.

Parameters

other

The other windows::basic_object_handle object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_object_handle(io_service&) constructor.

Cancel all asynchronous operations associated with the handle.

void cancel();
  » more...

boost::system::error_code cancel(
    boost::system::error_code & ec);
  » more...

Inherited from windows::basic_handle.

Cancel all asynchronous operations associated with the handle.

void cancel();

This function causes all outstanding asynchronous read or write operations to finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error.

Exceptions

boost::system::system_error

Thrown on failure.

Inherited from windows::basic_handle.

Cancel all asynchronous operations associated with the handle.

boost::system::error_code cancel(
    boost::system::error_code & ec);

This function causes all outstanding asynchronous read or write operations to finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error.

Parameters

ec

Set to indicate what error occurred, if any.

Close the handle.

void close();
  » more...

boost::system::error_code close(
    boost::system::error_code & ec);
  » more...

Inherited from windows::basic_handle.

Close the handle.

void close();

This function is used to close the handle. Any asynchronous read or write operations will be cancelled immediately, and will complete with the boost::asio::error::operation_aborted error.

Exceptions

boost::system::system_error

Thrown on failure.

Inherited from windows::basic_handle.

Close the handle.

boost::system::error_code close(
    boost::system::error_code & ec);

This function is used to close the handle. Any asynchronous read or write operations will be cancelled immediately, and will complete with the boost::asio::error::operation_aborted error.

Parameters

ec

Set to indicate what error occurred, if any.

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();
  » more...

const implementation_type & get_implementation() const;
  » more...

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

const implementation_type & get_implementation() const;

Inherited from basic_io_object.

Get the io_service associated with the object.

boost::asio::io_service & get_io_service();

This function may be used to obtain the io_service object that the I/O object uses to dispatch handlers for asynchronous operations.

Return Value

A reference to the io_service object that the I/O object will use to dispatch handlers. Ownership is not transferred to the caller.

Get the service associated with the I/O object.

service_type & get_service();
  » more...

const service_type & get_service() const;
  » more...

Inherited from basic_io_object.

Get the service associated with the I/O object.

service_type & get_service();

Inherited from basic_io_object.

Get the service associated with the I/O object.

const service_type & get_service() const;

Inherited from basic_io_object.

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

implementation_type implementation;

Inherited from basic_io_object.

The underlying implementation type of I/O object.

typedef service_type::implementation_type implementation_type;
Requirements

Header: boost/asio/windows/basic_object_handle.hpp

Convenience header: boost/asio.hpp

Inherited from windows::basic_handle.

Determine whether the handle is open.

bool is_open() const;

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();
  » more...

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;
  » more...

Inherited from windows::basic_handle.

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();

This function returns a reference to the lowest layer in a stack of layers. Since a windows::basic_handle cannot contain any further layers, it simply returns a reference to itself.

Return Value

A reference to the lowest layer in the stack of layers. Ownership is not transferred to the caller.

Inherited from windows::basic_handle.

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;

This function returns a const reference to the lowest layer in a stack of layers. Since a windows::basic_handle cannot contain any further layers, it simply returns a reference to itself.

Return Value

A const reference to the lowest layer in the stack of layers. Ownership is not transferred to the caller.

Inherited from windows::basic_handle.

A windows::basic_handle is always the lowest layer.

typedef basic_handle< ObjectHandleService > lowest_layer_type;
Types

Name

Description

implementation_type

The underlying implementation type of I/O object.

lowest_layer_type

A basic_handle is always the lowest layer.

native_handle_type

The native representation of a handle.

native_type

(Deprecated: Use native_handle_type.) The native representation of a handle.

service_type

The type of the service that will be used to provide I/O operations.

Member Functions

Name

Description

assign

Assign an existing native handle to the handle.

basic_handle

Construct a basic_handle without opening it.

Construct a basic_handle on an existing native handle.

Move-construct a basic_handle from another.

cancel

Cancel all asynchronous operations associated with the handle.

close

Close the handle.

get_io_service

Get the io_service associated with the object.

is_open

Determine whether the handle is open.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native handle representation.

native_handle

Get the native handle representation.

operator=

Move-assign a basic_handle from another.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

~basic_handle

Protected destructor to prevent deletion through this type.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The windows::basic_handle class template provides the ability to wrap a Windows handle.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/windows/basic_object_handle.hpp

Convenience header: boost/asio.hpp

Inherited from windows::basic_handle.

(Deprecated: Use native_handle().) Get the native handle representation.

native_type native();

This function may be used to obtain the underlying representation of the handle. This is intended to allow access to native handle functionality that is not otherwise provided.

Inherited from windows::basic_handle.

Get the native handle representation.

native_handle_type native_handle();

This function may be used to obtain the underlying representation of the handle. This is intended to allow access to native handle functionality that is not otherwise provided.

The native representation of a handle.

typedef ObjectHandleService::native_handle_type native_handle_type;
Requirements

Header: boost/asio/windows/basic_object_handle.hpp

Convenience header: boost/asio.hpp

Inherited from windows::basic_handle.

(Deprecated: Use native_handle_type.) The native representation of a handle.

typedef ObjectHandleService::native_handle_type native_type;
Requirements

Header: boost/asio/windows/basic_object_handle.hpp

Convenience header: boost/asio.hpp

Move-assign a windows::basic_object_handle from another.

basic_object_handle & operator=(
    basic_object_handle && other);

This assignment operator moves an object handle from one object to another.

Parameters

other

The other windows::basic_object_handle object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_object_handle(io_service&) constructor.

Inherited from basic_io_object.

(Deprecated: Use get_service().) The service associated with the I/O object.

service_type & service;
Remarks

Available only for services that do not support movability.

Inherited from basic_io_object.

The type of the service that will be used to provide I/O operations.

typedef ObjectHandleService service_type;
Requirements

Header: boost/asio/windows/basic_object_handle.hpp

Convenience header: boost/asio.hpp

Perform a blocking wait on the object handle.

void wait();
  » more...

void wait(
    boost::system::error_code & ec);
  » more...

Perform a blocking wait on the object handle.

void wait();

This function is used to wait for the object handle to be set to the signalled state. This function blocks and does not return until the object handle has been set to the signalled state.

Exceptions

boost::system::system_error

Thrown on failure.

Perform a blocking wait on the object handle.

void wait(
    boost::system::error_code & ec);

This function is used to wait for the object handle to be set to the signalled state. This function blocks and does not return until the object handle has been set to the signalled state.

Parameters

ec

Set to indicate what error occurred, if any.

Provides random-access handle functionality.

template<
    typename RandomAccessHandleService = random_access_handle_service>
class basic_random_access_handle :
  public windows::basic_handle< RandomAccessHandleService >
Types

Name

Description

implementation_type

The underlying implementation type of I/O object.

lowest_layer_type

A basic_handle is always the lowest layer.

native_handle_type

The native representation of a handle.

native_type

(Deprecated: Use native_handle_type.) The native representation of a handle.

service_type

The type of the service that will be used to provide I/O operations.

Member Functions

Name

Description

assign

Assign an existing native handle to the handle.

async_read_some_at

Start an asynchronous read at the specified offset.

async_write_some_at

Start an asynchronous write at the specified offset.

basic_random_access_handle

Construct a basic_random_access_handle without opening it.

Construct a basic_random_access_handle on an existing native handle.

Move-construct a basic_random_access_handle from another.

cancel

Cancel all asynchronous operations associated with the handle.

close

Close the handle.

get_io_service

Get the io_service associated with the object.

is_open

Determine whether the handle is open.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native handle representation.

native_handle

Get the native handle representation.

operator=

Move-assign a basic_random_access_handle from another.

read_some_at

Read some data from the handle at the specified offset.

write_some_at

Write some data to the handle at the specified offset.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The windows::basic_random_access_handle class template provides asynchronous and blocking random-access handle functionality.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/windows/basic_random_access_handle.hpp

Convenience header: boost/asio.hpp

Assign an existing native handle to the handle.

void assign(
    const native_handle_type & handle);
  » more...

boost::system::error_code assign(
    const native_handle_type & handle,
    boost::system::error_code & ec);
  » more...

Inherited from windows::basic_handle.

Assign an existing native handle to the handle.

void assign(
    const native_handle_type & handle);

Inherited from windows::basic_handle.

Assign an existing native handle to the handle.

boost::system::error_code assign(
    const native_handle_type & handle,
    boost::system::error_code & ec);

Start an asynchronous read at the specified offset.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_read_some_at(
    uint64_t offset,
    const MutableBufferSequence & buffers,
    ReadHandler handler);

This function is used to asynchronously read data from the random-access handle. The function call always returns immediately.

Parameters

offset

The offset at which the data will be read.

buffers

One or more buffers into which the data will be read. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

handler

The handler to be called when the read operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes read.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

The read operation may not read all of the requested number of bytes. Consider using the async_read_at function if you need to ensure that the requested amount of data is read before the asynchronous operation completes.

Example

To read into a single data buffer use the buffer function as follows:

handle.async_read_some_at(42, boost::asio::buffer(data, size), handler);

See the buffer documentation for information on reading into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Start an asynchronous write at the specified offset.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_write_some_at(
    uint64_t offset,
    const ConstBufferSequence & buffers,
    WriteHandler handler);

This function is used to asynchronously write data to the random-access handle. The function call always returns immediately.

Parameters

offset

The offset at which the data will be written.

buffers

One or more data buffers to be written to the handle. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

handler

The handler to be called when the write operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes written.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

The write operation may not transmit all of the data to the peer. Consider using the async_write_at function if you need to ensure that all data is written before the asynchronous operation completes.

Example

To write a single data buffer use the buffer function as follows:

handle.async_write_some_at(42, boost::asio::buffer(data, size), handler);

See the buffer documentation for information on writing multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Construct a windows::basic_random_access_handle without opening it.

explicit basic_random_access_handle(
    boost::asio::io_service & io_service);
  » more...

Construct a windows::basic_random_access_handle on an existing native handle.

basic_random_access_handle(
    boost::asio::io_service & io_service,
    const native_handle_type & handle);
  » more...

Move-construct a windows::basic_random_access_handle from another.

basic_random_access_handle(
    basic_random_access_handle && other);
  » more...

Construct a windows::basic_random_access_handle without opening it.

basic_random_access_handle(
    boost::asio::io_service & io_service);

This constructor creates a random-access handle without opening it. The handle needs to be opened before data can be written to or read from it.

Parameters

io_service

The io_service object that the random-access handle will use to dispatch handlers for any asynchronous operations performed on the handle.

Construct a windows::basic_random_access_handle on an existing native handle.

basic_random_access_handle(
    boost::asio::io_service & io_service,
    const native_handle_type & handle);

This constructor creates a random-access handle object to hold an existing native handle.

Parameters

io_service

The io_service object that the random-access handle will use to dispatch handlers for any asynchronous operations performed on the handle.

handle

The new underlying handle implementation.

Exceptions

boost::system::system_error

Thrown on failure.

Move-construct a windows::basic_random_access_handle from another.

basic_random_access_handle(
    basic_random_access_handle && other);

This constructor moves a random-access handle from one object to another.

Parameters

other

The other windows::basic_random_access_handle object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_random_access_handle(io_service&) constructor.

Cancel all asynchronous operations associated with the handle.

void cancel();
  » more...

boost::system::error_code cancel(
    boost::system::error_code & ec);
  » more...

Inherited from windows::basic_handle.

Cancel all asynchronous operations associated with the handle.

void cancel();

This function causes all outstanding asynchronous read or write operations to finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error.

Exceptions

boost::system::system_error

Thrown on failure.

Inherited from windows::basic_handle.

Cancel all asynchronous operations associated with the handle.

boost::system::error_code cancel(
    boost::system::error_code & ec);

This function causes all outstanding asynchronous read or write operations to finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error.

Parameters

ec

Set to indicate what error occurred, if any.

Close the handle.

void close();
  » more...

boost::system::error_code close(
    boost::system::error_code & ec);
  » more...

Inherited from windows::basic_handle.

Close the handle.

void close();

This function is used to close the handle. Any asynchronous read or write operations will be cancelled immediately, and will complete with the boost::asio::error::operation_aborted error.

Exceptions

boost::system::system_error

Thrown on failure.

Inherited from windows::basic_handle.

Close the handle.

boost::system::error_code close(
    boost::system::error_code & ec);

This function is used to close the handle. Any asynchronous read or write operations will be cancelled immediately, and will complete with the boost::asio::error::operation_aborted error.

Parameters

ec

Set to indicate what error occurred, if any.

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();
  » more...

const implementation_type & get_implementation() const;
  » more...

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

const implementation_type & get_implementation() const;

Inherited from basic_io_object.

Get the io_service associated with the object.

boost::asio::io_service & get_io_service();

This function may be used to obtain the io_service object that the I/O object uses to dispatch handlers for asynchronous operations.

Return Value

A reference to the io_service object that the I/O object will use to dispatch handlers. Ownership is not transferred to the caller.

Get the service associated with the I/O object.

service_type & get_service();
  » more...

const service_type & get_service() const;
  » more...

Inherited from basic_io_object.

Get the service associated with the I/O object.

service_type & get_service();

Inherited from basic_io_object.

Get the service associated with the I/O object.

const service_type & get_service() const;

Inherited from basic_io_object.

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

implementation_type implementation;

Inherited from basic_io_object.

The underlying implementation type of I/O object.

typedef service_type::implementation_type implementation_type;
Requirements

Header: boost/asio/windows/basic_random_access_handle.hpp

Convenience header: boost/asio.hpp

Inherited from windows::basic_handle.

Determine whether the handle is open.

bool is_open() const;

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();
  » more...

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;
  » more...

Inherited from windows::basic_handle.

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();

This function returns a reference to the lowest layer in a stack of layers. Since a windows::basic_handle cannot contain any further layers, it simply returns a reference to itself.

Return Value

A reference to the lowest layer in the stack of layers. Ownership is not transferred to the caller.

Inherited from windows::basic_handle.

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;

This function returns a const reference to the lowest layer in a stack of layers. Since a windows::basic_handle cannot contain any further layers, it simply returns a reference to itself.

Return Value

A const reference to the lowest layer in the stack of layers. Ownership is not transferred to the caller.

Inherited from windows::basic_handle.

A windows::basic_handle is always the lowest layer.

typedef basic_handle< RandomAccessHandleService > lowest_layer_type;
Types

Name

Description

implementation_type

The underlying implementation type of I/O object.

lowest_layer_type

A basic_handle is always the lowest layer.

native_handle_type

The native representation of a handle.

native_type

(Deprecated: Use native_handle_type.) The native representation of a handle.

service_type

The type of the service that will be used to provide I/O operations.

Member Functions

Name

Description

assign

Assign an existing native handle to the handle.

basic_handle

Construct a basic_handle without opening it.

Construct a basic_handle on an existing native handle.

Move-construct a basic_handle from another.

cancel

Cancel all asynchronous operations associated with the handle.

close

Close the handle.

get_io_service

Get the io_service associated with the object.

is_open

Determine whether the handle is open.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native handle representation.

native_handle

Get the native handle representation.

operator=

Move-assign a basic_handle from another.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

~basic_handle

Protected destructor to prevent deletion through this type.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The windows::basic_handle class template provides the ability to wrap a Windows handle.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/windows/basic_random_access_handle.hpp

Convenience header: boost/asio.hpp

Inherited from windows::basic_handle.

(Deprecated: Use native_handle().) Get the native handle representation.

native_type native();

This function may be used to obtain the underlying representation of the handle. This is intended to allow access to native handle functionality that is not otherwise provided.

Inherited from windows::basic_handle.

Get the native handle representation.

native_handle_type native_handle();

This function may be used to obtain the underlying representation of the handle. This is intended to allow access to native handle functionality that is not otherwise provided.

The native representation of a handle.

typedef RandomAccessHandleService::native_handle_type native_handle_type;
Requirements

Header: boost/asio/windows/basic_random_access_handle.hpp

Convenience header: boost/asio.hpp

(Deprecated: Use native_handle_type.) The native representation of a handle.

typedef RandomAccessHandleService::native_handle_type native_type;
Requirements

Header: boost/asio/windows/basic_random_access_handle.hpp

Convenience header: boost/asio.hpp

Move-assign a windows::basic_random_access_handle from another.

basic_random_access_handle & operator=(
    basic_random_access_handle && other);

This assignment operator moves a random-access handle from one object to another.

Parameters

other

The other windows::basic_random_access_handle object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_random_access_handle(io_service&) constructor.

Read some data from the handle at the specified offset.

template<
    typename MutableBufferSequence>
std::size_t read_some_at(
    uint64_t offset,
    const MutableBufferSequence & buffers);
  » more...

template<
    typename MutableBufferSequence>
std::size_t read_some_at(
    uint64_t offset,
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);
  » more...

Read some data from the handle at the specified offset.

template<
    typename MutableBufferSequence>
std::size_t read_some_at(
    uint64_t offset,
    const MutableBufferSequence & buffers);

This function is used to read data from the random-access handle. The function call will block until one or more bytes of data has been read successfully, or until an error occurs.

Parameters

offset

The offset at which the data will be read.

buffers

One or more buffers into which the data will be read.

Return Value

The number of bytes read.

Exceptions

boost::system::system_error

Thrown on failure. An error code of boost::asio::error::eof indicates that the connection was closed by the peer.

Remarks

The read_some operation may not read all of the requested number of bytes. Consider using the read_at function if you need to ensure that the requested amount of data is read before the blocking operation completes.

Example

To read into a single data buffer use the buffer function as follows:

handle.read_some_at(42, boost::asio::buffer(data, size));

See the buffer documentation for information on reading into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Read some data from the handle at the specified offset.

template<
    typename MutableBufferSequence>
std::size_t read_some_at(
    uint64_t offset,
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);

This function is used to read data from the random-access handle. The function call will block until one or more bytes of data has been read successfully, or until an error occurs.

Parameters

offset

The offset at which the data will be read.

buffers

One or more buffers into which the data will be read.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes read. Returns 0 if an error occurred.

Remarks

The read_some operation may not read all of the requested number of bytes. Consider using the read_at function if you need to ensure that the requested amount of data is read before the blocking operation completes.

Inherited from basic_io_object.

(Deprecated: Use get_service().) The service associated with the I/O object.

service_type & service;
Remarks

Available only for services that do not support movability.

Inherited from basic_io_object.

The type of the service that will be used to provide I/O operations.

typedef RandomAccessHandleService service_type;
Requirements

Header: boost/asio/windows/basic_random_access_handle.hpp

Convenience header: boost/asio.hpp

Write some data to the handle at the specified offset.

template<
    typename ConstBufferSequence>
std::size_t write_some_at(
    uint64_t offset,
    const ConstBufferSequence & buffers);
  » more...

template<
    typename ConstBufferSequence>
std::size_t write_some_at(
    uint64_t offset,
    const ConstBufferSequence & buffers,
    boost::system::error_code & ec);
  » more...

Write some data to the handle at the specified offset.

template<
    typename ConstBufferSequence>
std::size_t write_some_at(
    uint64_t offset,
    const ConstBufferSequence & buffers);

This function is used to write data to the random-access handle. The function call will block until one or more bytes of the data has been written successfully, or until an error occurs.

Parameters

offset

The offset at which the data will be written.

buffers

One or more data buffers to be written to the handle.

Return Value

The number of bytes written.

Exceptions

boost::system::system_error

Thrown on failure. An error code of boost::asio::error::eof indicates that the connection was closed by the peer.

Remarks

The write_some_at operation may not write all of the data. Consider using the write_at function if you need to ensure that all data is written before the blocking operation completes.

Example

To write a single data buffer use the buffer function as follows:

handle.write_some_at(42, boost::asio::buffer(data, size));

See the buffer documentation for information on writing multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Write some data to the handle at the specified offset.

template<
    typename ConstBufferSequence>
std::size_t write_some_at(
    uint64_t offset,
    const ConstBufferSequence & buffers,
    boost::system::error_code & ec);

This function is used to write data to the random-access handle. The function call will block until one or more bytes of the data has been written successfully, or until an error occurs.

Parameters

offset

The offset at which the data will be written.

buffers

One or more data buffers to be written to the handle.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes written. Returns 0 if an error occurred.

Remarks

The write_some operation may not transmit all of the data to the peer. Consider using the write_at function if you need to ensure that all data is written before the blocking operation completes.

Provides stream-oriented handle functionality.

template<
    typename StreamHandleService = stream_handle_service>
class basic_stream_handle :
  public windows::basic_handle< StreamHandleService >
Types

Name

Description

implementation_type

The underlying implementation type of I/O object.

lowest_layer_type

A basic_handle is always the lowest layer.

native_handle_type

The native representation of a handle.

native_type

(Deprecated: Use native_handle_type.) The native representation of a handle.

service_type

The type of the service that will be used to provide I/O operations.

Member Functions

Name

Description

assign

Assign an existing native handle to the handle.

async_read_some

Start an asynchronous read.

async_write_some

Start an asynchronous write.

basic_stream_handle

Construct a basic_stream_handle without opening it.

Construct a basic_stream_handle on an existing native handle.

Move-construct a basic_stream_handle from another.

cancel

Cancel all asynchronous operations associated with the handle.

close

Close the handle.

get_io_service

Get the io_service associated with the object.

is_open

Determine whether the handle is open.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native handle representation.

native_handle

Get the native handle representation.

operator=

Move-assign a basic_stream_handle from another.

read_some

Read some data from the handle.

write_some

Write some data to the handle.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The windows::basic_stream_handle class template provides asynchronous and blocking stream-oriented handle functionality.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/windows/basic_stream_handle.hpp

Convenience header: boost/asio.hpp

Assign an existing native handle to the handle.

void assign(
    const native_handle_type & handle);
  » more...

boost::system::error_code assign(
    const native_handle_type & handle,
    boost::system::error_code & ec);
  » more...

Inherited from windows::basic_handle.

Assign an existing native handle to the handle.

void assign(
    const native_handle_type & handle);

Inherited from windows::basic_handle.

Assign an existing native handle to the handle.

boost::system::error_code assign(
    const native_handle_type & handle,
    boost::system::error_code & ec);

Start an asynchronous read.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_read_some(
    const MutableBufferSequence & buffers,
    ReadHandler handler);

This function is used to asynchronously read data from the stream handle. The function call always returns immediately.

Parameters

buffers

One or more buffers into which the data will be read. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

handler

The handler to be called when the read operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes read.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

The read operation may not read all of the requested number of bytes. Consider using the async_read function if you need to ensure that the requested amount of data is read before the asynchronous operation completes.

Example

To read into a single data buffer use the buffer function as follows:

handle.async_read_some(boost::asio::buffer(data, size), handler);

See the buffer documentation for information on reading into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Start an asynchronous write.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_write_some(
    const ConstBufferSequence & buffers,
    WriteHandler handler);

This function is used to asynchronously write data to the stream handle. The function call always returns immediately.

Parameters

buffers

One or more data buffers to be written to the handle. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

handler

The handler to be called when the write operation completes. Copies will be made of the handler as required. The function signature of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes written.
);

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Remarks

The write operation may not transmit all of the data to the peer. Consider using the async_write function if you need to ensure that all data is written before the asynchronous operation completes.

Example

To write a single data buffer use the buffer function as follows:

handle.async_write_some(boost::asio::buffer(data, size), handler);

See the buffer documentation for information on writing multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Construct a windows::basic_stream_handle without opening it.

explicit basic_stream_handle(
    boost::asio::io_service & io_service);
  » more...

Construct a windows::basic_stream_handle on an existing native handle.

basic_stream_handle(
    boost::asio::io_service & io_service,
    const native_handle_type & handle);
  » more...

Move-construct a windows::basic_stream_handle from another.

basic_stream_handle(
    basic_stream_handle && other);
  » more...

Construct a windows::basic_stream_handle without opening it.

basic_stream_handle(
    boost::asio::io_service & io_service);

This constructor creates a stream handle without opening it. The handle needs to be opened and then connected or accepted before data can be sent or received on it.

Parameters

io_service

The io_service object that the stream handle will use to dispatch handlers for any asynchronous operations performed on the handle.

Construct a windows::basic_stream_handle on an existing native handle.

basic_stream_handle(
    boost::asio::io_service & io_service,
    const native_handle_type & handle);

This constructor creates a stream handle object to hold an existing native handle.

Parameters

io_service

The io_service object that the stream handle will use to dispatch handlers for any asynchronous operations performed on the handle.

handle

The new underlying handle implementation.

Exceptions

boost::system::system_error

Thrown on failure.

Move-construct a windows::basic_stream_handle from another.

basic_stream_handle(
    basic_stream_handle && other);

This constructor moves a stream handle from one object to another.

Parameters

other

The other windows::basic_stream_handle object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_stream_handle(io_service&) constructor.

Cancel all asynchronous operations associated with the handle.

void cancel();
  » more...

boost::system::error_code cancel(
    boost::system::error_code & ec);
  » more...

Inherited from windows::basic_handle.

Cancel all asynchronous operations associated with the handle.

void cancel();

This function causes all outstanding asynchronous read or write operations to finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error.

Exceptions

boost::system::system_error

Thrown on failure.

Inherited from windows::basic_handle.

Cancel all asynchronous operations associated with the handle.

boost::system::error_code cancel(
    boost::system::error_code & ec);

This function causes all outstanding asynchronous read or write operations to finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error.

Parameters

ec

Set to indicate what error occurred, if any.

Close the handle.

void close();
  » more...

boost::system::error_code close(
    boost::system::error_code & ec);
  » more...

Inherited from windows::basic_handle.

Close the handle.

void close();

This function is used to close the handle. Any asynchronous read or write operations will be cancelled immediately, and will complete with the boost::asio::error::operation_aborted error.

Exceptions

boost::system::system_error

Thrown on failure.

Inherited from windows::basic_handle.

Close the handle.

boost::system::error_code close(
    boost::system::error_code & ec);

This function is used to close the handle. Any asynchronous read or write operations will be cancelled immediately, and will complete with the boost::asio::error::operation_aborted error.

Parameters

ec

Set to indicate what error occurred, if any.

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();
  » more...

const implementation_type & get_implementation() const;
  » more...

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

implementation_type & get_implementation();

Inherited from basic_io_object.

Get the underlying implementation of the I/O object.

const implementation_type & get_implementation() const;

Inherited from basic_io_object.

Get the io_service associated with the object.

boost::asio::io_service & get_io_service();

This function may be used to obtain the io_service object that the I/O object uses to dispatch handlers for asynchronous operations.

Return Value

A reference to the io_service object that the I/O object will use to dispatch handlers. Ownership is not transferred to the caller.

Get the service associated with the I/O object.

service_type & get_service();
  » more...

const service_type & get_service() const;
  » more...

Inherited from basic_io_object.

Get the service associated with the I/O object.

service_type & get_service();

Inherited from basic_io_object.

Get the service associated with the I/O object.

const service_type & get_service() const;

Inherited from basic_io_object.

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

implementation_type implementation;

Inherited from basic_io_object.

The underlying implementation type of I/O object.

typedef service_type::implementation_type implementation_type;
Requirements

Header: boost/asio/windows/basic_stream_handle.hpp

Convenience header: boost/asio.hpp

Inherited from windows::basic_handle.

Determine whether the handle is open.

bool is_open() const;

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();
  » more...

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;
  » more...

Inherited from windows::basic_handle.

Get a reference to the lowest layer.

lowest_layer_type & lowest_layer();

This function returns a reference to the lowest layer in a stack of layers. Since a windows::basic_handle cannot contain any further layers, it simply returns a reference to itself.

Return Value

A reference to the lowest layer in the stack of layers. Ownership is not transferred to the caller.

Inherited from windows::basic_handle.

Get a const reference to the lowest layer.

const lowest_layer_type & lowest_layer() const;

This function returns a const reference to the lowest layer in a stack of layers. Since a windows::basic_handle cannot contain any further layers, it simply returns a reference to itself.

Return Value

A const reference to the lowest layer in the stack of layers. Ownership is not transferred to the caller.

Inherited from windows::basic_handle.

A windows::basic_handle is always the lowest layer.

typedef basic_handle< StreamHandleService > lowest_layer_type;
Types

Name

Description

implementation_type

The underlying implementation type of I/O object.

lowest_layer_type

A basic_handle is always the lowest layer.

native_handle_type

The native representation of a handle.

native_type

(Deprecated: Use native_handle_type.) The native representation of a handle.

service_type

The type of the service that will be used to provide I/O operations.

Member Functions

Name

Description

assign

Assign an existing native handle to the handle.

basic_handle

Construct a basic_handle without opening it.

Construct a basic_handle on an existing native handle.

Move-construct a basic_handle from another.

cancel

Cancel all asynchronous operations associated with the handle.

close

Close the handle.

get_io_service

Get the io_service associated with the object.

is_open

Determine whether the handle is open.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native handle representation.

native_handle

Get the native handle representation.

operator=

Move-assign a basic_handle from another.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

~basic_handle

Protected destructor to prevent deletion through this type.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The windows::basic_handle class template provides the ability to wrap a Windows handle.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/windows/basic_stream_handle.hpp

Convenience header: boost/asio.hpp

Inherited from windows::basic_handle.

(Deprecated: Use native_handle().) Get the native handle representation.

native_type native();

This function may be used to obtain the underlying representation of the handle. This is intended to allow access to native handle functionality that is not otherwise provided.

Inherited from windows::basic_handle.

Get the native handle representation.

native_handle_type native_handle();

This function may be used to obtain the underlying representation of the handle. This is intended to allow access to native handle functionality that is not otherwise provided.

The native representation of a handle.

typedef StreamHandleService::native_handle_type native_handle_type;
Requirements

Header: boost/asio/windows/basic_stream_handle.hpp

Convenience header: boost/asio.hpp

(Deprecated: Use native_handle_type.) The native representation of a handle.

typedef StreamHandleService::native_handle_type native_type;
Requirements

Header: boost/asio/windows/basic_stream_handle.hpp

Convenience header: boost/asio.hpp

Move-assign a windows::basic_stream_handle from another.

basic_stream_handle & operator=(
    basic_stream_handle && other);

This assignment operator moves a stream handle from one object to another.

Parameters

other

The other windows::basic_stream_handle object from which the move will occur.

Remarks

Following the move, the moved-from object is in the same state as if constructed using the basic_stream_handle(io_service&) constructor.

Read some data from the handle.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers);
  » more...

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);
  » more...

Read some data from the handle.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers);

This function is used to read data from the stream handle. The function call will block until one or more bytes of data has been read successfully, or until an error occurs.

Parameters

buffers

One or more buffers into which the data will be read.

Return Value

The number of bytes read.

Exceptions

boost::system::system_error

Thrown on failure. An error code of boost::asio::error::eof indicates that the connection was closed by the peer.

Remarks

The read_some operation may not read all of the requested number of bytes. Consider using the read function if you need to ensure that the requested amount of data is read before the blocking operation completes.

Example

To read into a single data buffer use the buffer function as follows:

handle.read_some(boost::asio::buffer(data, size));

See the buffer documentation for information on reading into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Read some data from the handle.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);

This function is used to read data from the stream handle. The function call will block until one or more bytes of data has been read successfully, or until an error occurs.

Parameters

buffers

One or more buffers into which the data will be read.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes read. Returns 0 if an error occurred.

Remarks

The read_some operation may not read all of the requested number of bytes. Consider using the read function if you need to ensure that the requested amount of data is read before the blocking operation completes.

Inherited from basic_io_object.

(Deprecated: Use get_service().) The service associated with the I/O object.

service_type & service;
Remarks

Available only for services that do not support movability.

Inherited from basic_io_object.

The type of the service that will be used to provide I/O operations.

typedef StreamHandleService service_type;
Requirements

Header: boost/asio/windows/basic_stream_handle.hpp

Convenience header: boost/asio.hpp

Write some data to the handle.

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers);
  » more...

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers,
    boost::system::error_code & ec);
  » more...

Write some data to the handle.

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers);

This function is used to write data to the stream handle. The function call will block until one or more bytes of the data has been written successfully, or until an error occurs.

Parameters

buffers

One or more data buffers to be written to the handle.

Return Value

The number of bytes written.

Exceptions

boost::system::system_error

Thrown on failure. An error code of boost::asio::error::eof indicates that the connection was closed by the peer.

Remarks

The write_some operation may not transmit all of the data to the peer. Consider using the write function if you need to ensure that all data is written before the blocking operation completes.

Example

To write a single data buffer use the buffer function as follows:

handle.write_some(boost::asio::buffer(data, size));

See the buffer documentation for information on writing multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Write some data to the handle.

template<
    typename ConstBufferSequence>
std::size_t write_some(
    const ConstBufferSequence & buffers,
    boost::system::error_code & ec);

This function is used to write data to the stream handle. The function call will block until one or more bytes of the data has been written successfully, or until an error occurs.

Parameters

buffers

One or more data buffers to be written to the handle.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes written. Returns 0 if an error occurred.

Remarks

The write_some operation may not transmit all of the data to the peer. Consider using the write function if you need to ensure that all data is written before the blocking operation completes.

Typedef for the typical usage of an object handle.

typedef basic_object_handle object_handle;
Types

Name

Description

implementation_type

The underlying implementation type of I/O object.

lowest_layer_type

A basic_handle is always the lowest layer.

native_handle_type

The native representation of a handle.

native_type

(Deprecated: Use native_handle_type.) The native representation of a handle.

service_type

The type of the service that will be used to provide I/O operations.

Member Functions

Name

Description

assign

Assign an existing native handle to the handle.

async_wait

Start an asynchronous wait on the object handle.

basic_object_handle

Construct a basic_object_handle without opening it.

Construct a basic_object_handle on an existing native handle.

Move-construct a basic_object_handle from another.

cancel

Cancel all asynchronous operations associated with the handle.

close

Close the handle.

get_io_service

Get the io_service associated with the object.

is_open

Determine whether the handle is open.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native handle representation.

native_handle

Get the native handle representation.

operator=

Move-assign a basic_object_handle from another.

wait

Perform a blocking wait on the object handle.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The windows::basic_object_handle class template provides asynchronous and blocking object-oriented handle functionality.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/windows/object_handle.hpp

Convenience header: boost/asio.hpp

Default service implementation for an object handle.

class object_handle_service :
  public io_service::service
Types

Name

Description

implementation_type

The type of an object handle implementation.

native_handle_type

The native handle type.

Member Functions

Name

Description

assign

Assign an existing native handle to an object handle.

async_wait

Start an asynchronous wait.

cancel

Cancel all asynchronous operations associated with the handle.

close

Close an object handle implementation.

construct

Construct a new object handle implementation.

destroy

Destroy an object handle implementation.

get_io_service

Get the io_service object that owns the service.

is_open

Determine whether the handle is open.

move_assign

Move-assign from another object handle implementation.

move_construct

Move-construct a new object handle implementation.

native_handle

Get the native handle implementation.

object_handle_service

Construct a new object handle service for the specified io_service.

wait

Data Members

Name

Description

id

The unique service identifier.

Requirements

Header: boost/asio/windows/object_handle_service.hpp

Convenience header: boost/asio.hpp

Assign an existing native handle to an object handle.

boost::system::error_code assign(
    implementation_type & impl,
    const native_handle_type & handle,
    boost::system::error_code & ec);

Start an asynchronous wait.

template<
    typename WaitHandler>
void-or-deduced async_wait(
    implementation_type & impl,
    WaitHandler handler);

Cancel all asynchronous operations associated with the handle.

boost::system::error_code cancel(
    implementation_type & impl,
    boost::system::error_code & ec);

Close an object handle implementation.

boost::system::error_code close(
    implementation_type & impl,
    boost::system::error_code & ec);

Construct a new object handle implementation.

void construct(
    implementation_type & impl);

Destroy an object handle implementation.

void destroy(
    implementation_type & impl);

Inherited from io_service.

Get the io_service object that owns the service.

boost::asio::io_service & get_io_service();

The unique service identifier.

static boost::asio::io_service::id id;

The type of an object handle implementation.

typedef implementation_defined implementation_type;
Requirements

Header: boost/asio/windows/object_handle_service.hpp

Convenience header: boost/asio.hpp

Determine whether the handle is open.

bool is_open(
    const implementation_type & impl) const;

Move-assign from another object handle implementation.

void move_assign(
    implementation_type & impl,
    object_handle_service & other_service,
    implementation_type & other_impl);

Move-construct a new object handle implementation.

void move_construct(
    implementation_type & impl,
    implementation_type & other_impl);

Get the native handle implementation.

native_handle_type native_handle(
    implementation_type & impl);

The native handle type.

typedef implementation_defined native_handle_type;
Requirements

Header: boost/asio/windows/object_handle_service.hpp

Convenience header: boost/asio.hpp

Construct a new object handle service for the specified io_service.

object_handle_service(
    boost::asio::io_service & io_service);

void wait(
    implementation_type & impl,
    boost::system::error_code & ec);

Wraps a handler to create an OVERLAPPED object for use with overlapped I/O.

class overlapped_ptr :
  noncopyable
Member Functions

Name

Description

complete

Post completion notification for overlapped operation. Releases ownership.

get

Get the contained OVERLAPPED object.

overlapped_ptr

Construct an empty overlapped_ptr.

Construct an overlapped_ptr to contain the specified handler.

release

Release ownership of the OVERLAPPED object.

reset

Reset to empty.

Reset to contain the specified handler, freeing any current OVERLAPPED object.

~overlapped_ptr

Destructor automatically frees the OVERLAPPED object unless released.

A special-purpose smart pointer used to wrap an application handler so that it can be passed as the LPOVERLAPPED argument to overlapped I/O functions.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/windows/overlapped_ptr.hpp

Convenience header: boost/asio.hpp

Post completion notification for overlapped operation. Releases ownership.

void complete(
    const boost::system::error_code & ec,
    std::size_t bytes_transferred);

Get the contained OVERLAPPED object.

OVERLAPPED * get();
  » more...

const OVERLAPPED * get() const;
  » more...

Get the contained OVERLAPPED object.

OVERLAPPED * get();

Get the contained OVERLAPPED object.

const OVERLAPPED * get() const;

Construct an empty windows::overlapped_ptr.

overlapped_ptr();
  » more...

Construct an windows::overlapped_ptr to contain the specified handler.

template<
    typename Handler>
explicit overlapped_ptr(
    boost::asio::io_service & io_service,
    Handler handler);
  » more...

Construct an windows::overlapped_ptr to contain the specified handler.

template<
    typename Handler>
overlapped_ptr(
    boost::asio::io_service & io_service,
    Handler handler);

Release ownership of the OVERLAPPED object.

OVERLAPPED * release();

Reset to empty.

void reset();
  » more...

Reset to contain the specified handler, freeing any current OVERLAPPED object.

template<
    typename Handler>
void reset(
    boost::asio::io_service & io_service,
    Handler handler);
  » more...

Reset to contain the specified handler, freeing any current OVERLAPPED object.

template<
    typename Handler>
void reset(
    boost::asio::io_service & io_service,
    Handler handler);

Destructor automatically frees the OVERLAPPED object unless released.

~overlapped_ptr();

Typedef for the typical usage of a random-access handle.

typedef basic_random_access_handle random_access_handle;
Types

Name

Description

implementation_type

The underlying implementation type of I/O object.

lowest_layer_type

A basic_handle is always the lowest layer.

native_handle_type

The native representation of a handle.

native_type

(Deprecated: Use native_handle_type.) The native representation of a handle.

service_type

The type of the service that will be used to provide I/O operations.

Member Functions

Name

Description

assign

Assign an existing native handle to the handle.

async_read_some_at

Start an asynchronous read at the specified offset.

async_write_some_at

Start an asynchronous write at the specified offset.

basic_random_access_handle

Construct a basic_random_access_handle without opening it.

Construct a basic_random_access_handle on an existing native handle.

Move-construct a basic_random_access_handle from another.

cancel

Cancel all asynchronous operations associated with the handle.

close

Close the handle.

get_io_service

Get the io_service associated with the object.

is_open

Determine whether the handle is open.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native handle representation.

native_handle

Get the native handle representation.

operator=

Move-assign a basic_random_access_handle from another.

read_some_at

Read some data from the handle at the specified offset.

write_some_at

Write some data to the handle at the specified offset.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The windows::basic_random_access_handle class template provides asynchronous and blocking random-access handle functionality.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/windows/random_access_handle.hpp

Convenience header: boost/asio.hpp

Default service implementation for a random-access handle.

class random_access_handle_service :
  public io_service::service
Types

Name

Description

implementation_type

The type of a random-access handle implementation.

native_handle_type

The native handle type.

native_type

(Deprecated: Use native_handle_type.) The native handle type.

Member Functions

Name

Description

assign

Assign an existing native handle to a random-access handle.

async_read_some_at

Start an asynchronous read at the specified offset.

async_write_some_at

Start an asynchronous write at the specified offset.

cancel

Cancel all asynchronous operations associated with the handle.

close

Close a random-access handle implementation.

construct

Construct a new random-access handle implementation.

destroy

Destroy a random-access handle implementation.

get_io_service

Get the io_service object that owns the service.

is_open

Determine whether the handle is open.

move_assign

Move-assign from another random-access handle implementation.

move_construct

Move-construct a new random-access handle implementation.

native

(Deprecated: Use native_handle().) Get the native handle implementation.

native_handle

Get the native handle implementation.

random_access_handle_service

Construct a new random-access handle service for the specified io_service.

read_some_at

Read some data from the specified offset.

write_some_at

Write the given data at the specified offset.

Data Members

Name

Description

id

The unique service identifier.

Requirements

Header: boost/asio/windows/random_access_handle_service.hpp

Convenience header: boost/asio.hpp

Assign an existing native handle to a random-access handle.

boost::system::error_code assign(
    implementation_type & impl,
    const native_handle_type & handle,
    boost::system::error_code & ec);

Start an asynchronous read at the specified offset.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_read_some_at(
    implementation_type & impl,
    uint64_t offset,
    const MutableBufferSequence & buffers,
    ReadHandler handler);

Start an asynchronous write at the specified offset.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_write_some_at(
    implementation_type & impl,
    uint64_t offset,
    const ConstBufferSequence & buffers,
    WriteHandler handler);

Cancel all asynchronous operations associated with the handle.

boost::system::error_code cancel(
    implementation_type & impl,
    boost::system::error_code & ec);

Close a random-access handle implementation.

boost::system::error_code close(
    implementation_type & impl,
    boost::system::error_code & ec);

Construct a new random-access handle implementation.

void construct(
    implementation_type & impl);

Destroy a random-access handle implementation.

void destroy(
    implementation_type & impl);

Inherited from io_service.

Get the io_service object that owns the service.

boost::asio::io_service & get_io_service();

The unique service identifier.

static boost::asio::io_service::id id;

The type of a random-access handle implementation.

typedef implementation_defined implementation_type;
Requirements

Header: boost/asio/windows/random_access_handle_service.hpp

Convenience header: boost/asio.hpp

Determine whether the handle is open.

bool is_open(
    const implementation_type & impl) const;

Move-assign from another random-access handle implementation.

void move_assign(
    implementation_type & impl,
    random_access_handle_service & other_service,
    implementation_type & other_impl);

Move-construct a new random-access handle implementation.

void move_construct(
    implementation_type & impl,
    implementation_type & other_impl);

(Deprecated: Use native_handle().) Get the native handle implementation.

native_type native(
    implementation_type & impl);

Get the native handle implementation.

native_handle_type native_handle(
    implementation_type & impl);

The native handle type.

typedef implementation_defined native_handle_type;
Requirements

Header: boost/asio/windows/random_access_handle_service.hpp

Convenience header: boost/asio.hpp

(Deprecated: Use native_handle_type.) The native handle type.

typedef implementation_defined native_type;
Requirements

Header: boost/asio/windows/random_access_handle_service.hpp

Convenience header: boost/asio.hpp

Construct a new random-access handle service for the specified io_service.

random_access_handle_service(
    boost::asio::io_service & io_service);

Read some data from the specified offset.

template<
    typename MutableBufferSequence>
std::size_t read_some_at(
    implementation_type & impl,
    uint64_t offset,
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);

Write the given data at the specified offset.

template<
    typename ConstBufferSequence>
std::size_t write_some_at(
    implementation_type & impl,
    uint64_t offset,
    const ConstBufferSequence & buffers,
    boost::system::error_code & ec);

Typedef for the typical usage of a stream-oriented handle.

typedef basic_stream_handle stream_handle;
Types

Name

Description

implementation_type

The underlying implementation type of I/O object.

lowest_layer_type

A basic_handle is always the lowest layer.

native_handle_type

The native representation of a handle.

native_type

(Deprecated: Use native_handle_type.) The native representation of a handle.

service_type

The type of the service that will be used to provide I/O operations.

Member Functions

Name

Description

assign

Assign an existing native handle to the handle.

async_read_some

Start an asynchronous read.

async_write_some

Start an asynchronous write.

basic_stream_handle

Construct a basic_stream_handle without opening it.

Construct a basic_stream_handle on an existing native handle.

Move-construct a basic_stream_handle from another.

cancel

Cancel all asynchronous operations associated with the handle.

close

Close the handle.

get_io_service

Get the io_service associated with the object.

is_open

Determine whether the handle is open.

lowest_layer

Get a reference to the lowest layer.

Get a const reference to the lowest layer.

native

(Deprecated: Use native_handle().) Get the native handle representation.

native_handle

Get the native handle representation.

operator=

Move-assign a basic_stream_handle from another.

read_some

Read some data from the handle.

write_some

Write some data to the handle.

Protected Member Functions

Name

Description

get_implementation

Get the underlying implementation of the I/O object.

get_service

Get the service associated with the I/O object.

Protected Data Members

Name

Description

implementation

(Deprecated: Use get_implementation().) The underlying implementation of the I/O object.

service

(Deprecated: Use get_service().) The service associated with the I/O object.

The windows::basic_stream_handle class template provides asynchronous and blocking stream-oriented handle functionality.

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe.

Requirements

Header: boost/asio/windows/stream_handle.hpp

Convenience header: boost/asio.hpp

Default service implementation for a stream handle.

class stream_handle_service :
  public io_service::service
Types

Name

Description

implementation_type

The type of a stream handle implementation.

native_handle_type

The native handle type.

native_type

(Deprecated: Use native_handle_type.) The native handle type.

Member Functions

Name

Description

assign

Assign an existing native handle to a stream handle.

async_read_some

Start an asynchronous read.

async_write_some

Start an asynchronous write.

cancel

Cancel all asynchronous operations associated with the handle.

close

Close a stream handle implementation.

construct

Construct a new stream handle implementation.

destroy

Destroy a stream handle implementation.

get_io_service

Get the io_service object that owns the service.

is_open

Determine whether the handle is open.

move_assign

Move-assign from another stream handle implementation.

move_construct

Move-construct a new stream handle implementation.

native

(Deprecated: Use native_handle().) Get the native handle implementation.

native_handle

Get the native handle implementation.

read_some

Read some data from the stream.

stream_handle_service

Construct a new stream handle service for the specified io_service.

write_some

Write the given data to the stream.

Data Members

Name

Description

id

The unique service identifier.

Requirements

Header: boost/asio/windows/stream_handle_service.hpp

Convenience header: boost/asio.hpp

Assign an existing native handle to a stream handle.

boost::system::error_code assign(
    implementation_type & impl,
    const native_handle_type & handle,
    boost::system::error_code & ec);

Start an asynchronous read.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void-or-deduced async_read_some(
    implementation_type & impl,
    const MutableBufferSequence & buffers,
    ReadHandler handler);

Start an asynchronous write.

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void-or-deduced async_write_some(
    implementation_type & impl,
    const ConstBufferSequence & buffers,
    WriteHandler handler);

Cancel all asynchronous operations associated with the handle.

boost::system::error_code cancel(
    implementation_type & impl,
    boost::system::error_code & ec);

Close a stream handle implementation.

boost::system::error_code close(
    implementation_type & impl,
    boost::system::error_code & ec);

Construct a new stream handle implementation.

void construct(
    implementation_type & impl);

Destroy a stream handle implementation.

void destroy(
    implementation_type & impl);

Inherited from io_service.

Get the io_service object that owns the service.

boost::asio::io_service & get_io_service();

The unique service identifier.

static boost::asio::io_service::id id;

The type of a stream handle implementation.

typedef implementation_defined implementation_type;
Requirements

Header: boost/asio/windows/stream_handle_service.hpp

Convenience header: boost/asio.hpp

Determine whether the handle is open.

bool is_open(
    const implementation_type & impl) const;

Move-assign from another stream handle implementation.

void move_assign(
    implementation_type & impl,
    stream_handle_service & other_service,
    implementation_type & other_impl);

Move-construct a new stream handle implementation.

void move_construct(
    implementation_type & impl,
    implementation_type & other_impl);

(Deprecated: Use native_handle().) Get the native handle implementation.

native_type native(
    implementation_type & impl);

Get the native handle implementation.

native_handle_type native_handle(
    implementation_type & impl);

The native handle type.

typedef implementation_defined native_handle_type;
Requirements

Header: boost/asio/windows/stream_handle_service.hpp

Convenience header: boost/asio.hpp

(Deprecated: Use native_handle_type.) The native handle type.

typedef implementation_defined native_type;
Requirements

Header: boost/asio/windows/stream_handle_service.hpp

Convenience header: boost/asio.hpp

Read some data from the stream.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    implementation_type & impl,
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);

Construct a new stream handle service for the specified io_service.

stream_handle_service(
    boost::asio::io_service & io_service);

Write the given data to the stream.

template<
    typename ConstBufferSequence>
std::size_t write_some(
    implementation_type & impl,
    const ConstBufferSequence & buffers,
    boost::system::error_code & ec);

Write a certain amount of data to a stream before returning.

template<
    typename SyncWriteStream,
    typename ConstBufferSequence>
std::size_t write(
    SyncWriteStream & s,
    const ConstBufferSequence & buffers);
  » more...

template<
    typename SyncWriteStream,
    typename ConstBufferSequence>
std::size_t write(
    SyncWriteStream & s,
    const ConstBufferSequence & buffers,
    boost::system::error_code & ec);
  » more...

template<
    typename SyncWriteStream,
    typename ConstBufferSequence,
    typename CompletionCondition>
std::size_t write(
    SyncWriteStream & s,
    const ConstBufferSequence & buffers,
    CompletionCondition completion_condition);
  » more...

template<
    typename SyncWriteStream,
    typename ConstBufferSequence,
    typename CompletionCondition>
std::size_t write(
    SyncWriteStream & s,
    const ConstBufferSequence & buffers,
    CompletionCondition completion_condition,
    boost::system::error_code & ec);
  » more...

template<
    typename SyncWriteStream,
    typename Allocator>
std::size_t write(
    SyncWriteStream & s,
    basic_streambuf< Allocator > & b);
  » more...

template<
    typename SyncWriteStream,
    typename Allocator>
std::size_t write(
    SyncWriteStream & s,
    basic_streambuf< Allocator > & b,
    boost::system::error_code & ec);
  » more...

template<
    typename SyncWriteStream,
    typename Allocator,
    typename CompletionCondition>
std::size_t write(
    SyncWriteStream & s,
    basic_streambuf< Allocator > & b,
    CompletionCondition completion_condition);
  » more...

template<
    typename SyncWriteStream,
    typename Allocator,
    typename CompletionCondition>
std::size_t write(
    SyncWriteStream & s,
    basic_streambuf< Allocator > & b,
    CompletionCondition completion_condition,
    boost::system::error_code & ec);
  » more...
Requirements

Header: boost/asio/write.hpp

Convenience header: boost/asio.hpp

Write all of the supplied data to a stream before returning.

template<
    typename SyncWriteStream,
    typename ConstBufferSequence>
std::size_t write(
    SyncWriteStream & s,
    const ConstBufferSequence & buffers);

This function is used to write a certain number of bytes of data to a stream. The call will block until one of the following conditions is true:

  • All of the data in the supplied buffers has been written. That is, the bytes transferred is equal to the sum of the buffer sizes.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the stream's write_some function.

Parameters

s

The stream to which the data is to be written. The type must support the SyncWriteStream concept.

buffers

One or more buffers containing the data to be written. The sum of the buffer sizes indicates the maximum number of bytes to write to the stream.

Return Value

The number of bytes transferred.

Exceptions

boost::system::system_error

Thrown on failure.

Example

To write a single data buffer use the buffer function as follows:

boost::asio::write(s, boost::asio::buffer(data, size));

See the buffer documentation for information on writing multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Remarks

This overload is equivalent to calling:

boost::asio::write(
    s, buffers,
    boost::asio::transfer_all());

Write all of the supplied data to a stream before returning.

template<
    typename SyncWriteStream,
    typename ConstBufferSequence>
std::size_t write(
    SyncWriteStream & s,
    const ConstBufferSequence & buffers,
    boost::system::error_code & ec);

This function is used to write a certain number of bytes of data to a stream. The call will block until one of the following conditions is true:

  • All of the data in the supplied buffers has been written. That is, the bytes transferred is equal to the sum of the buffer sizes.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the stream's write_some function.

Parameters

s

The stream to which the data is to be written. The type must support the SyncWriteStream concept.

buffers

One or more buffers containing the data to be written. The sum of the buffer sizes indicates the maximum number of bytes to write to the stream.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes transferred.

Example

To write a single data buffer use the buffer function as follows:

boost::asio::write(s, boost::asio::buffer(data, size), ec);

See the buffer documentation for information on writing multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Remarks

This overload is equivalent to calling:

boost::asio::write(
    s, buffers,
    boost::asio::transfer_all(), ec);

Write a certain amount of data to a stream before returning.

template<
    typename SyncWriteStream,
    typename ConstBufferSequence,
    typename CompletionCondition>
std::size_t write(
    SyncWriteStream & s,
    const ConstBufferSequence & buffers,
    CompletionCondition completion_condition);

This function is used to write a certain number of bytes of data to a stream. The call will block until one of the following conditions is true:

  • All of the data in the supplied buffers has been written. That is, the bytes transferred is equal to the sum of the buffer sizes.
  • The completion_condition function object returns 0.

This operation is implemented in terms of zero or more calls to the stream's write_some function.

Parameters

s

The stream to which the data is to be written. The type must support the SyncWriteStream concept.

buffers

One or more buffers containing the data to be written. The sum of the buffer sizes indicates the maximum number of bytes to write to the stream.

completion_condition

The function object to be called to determine whether the write operation is complete. The signature of the function object must be:

std::size_t completion_condition(
  // Result of latest write_some operation.
  const boost::system::error_code& error,

  // Number of bytes transferred so far.
  std::size_t bytes_transferred
);

A return value of 0 indicates that the write operation is complete. A non-zero return value indicates the maximum number of bytes to be written on the next call to the stream's write_some function.

Return Value

The number of bytes transferred.

Exceptions

boost::system::system_error

Thrown on failure.

Example

To write a single data buffer use the buffer function as follows:

boost::asio::write(s, boost::asio::buffer(data, size),
    boost::asio::transfer_at_least(32));

See the buffer documentation for information on writing multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Write a certain amount of data to a stream before returning.

template<
    typename SyncWriteStream,
    typename ConstBufferSequence,
    typename CompletionCondition>
std::size_t write(
    SyncWriteStream & s,
    const ConstBufferSequence & buffers,
    CompletionCondition completion_condition,
    boost::system::error_code & ec);

This function is used to write a certain number of bytes of data to a stream. The call will block until one of the following conditions is true:

  • All of the data in the supplied buffers has been written. That is, the bytes transferred is equal to the sum of the buffer sizes.
  • The completion_condition function object returns 0.

This operation is implemented in terms of zero or more calls to the stream's write_some function.

Parameters

s

The stream to which the data is to be written. The type must support the SyncWriteStream concept.

buffers

One or more buffers containing the data to be written. The sum of the buffer sizes indicates the maximum number of bytes to write to the stream.

completion_condition

The function object to be called to determine whether the write operation is complete. The signature of the function object must be:

std::size_t completion_condition(
  // Result of latest write_some operation.
  const boost::system::error_code& error,

  // Number of bytes transferred so far.
  std::size_t bytes_transferred
);

A return value of 0 indicates that the write operation is complete. A non-zero return value indicates the maximum number of bytes to be written on the next call to the stream's write_some function.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes written. If an error occurs, returns the total number of bytes successfully transferred prior to the error.

Write all of the supplied data to a stream before returning.

template<
    typename SyncWriteStream,
    typename Allocator>
std::size_t write(
    SyncWriteStream & s,
    basic_streambuf< Allocator > & b);

This function is used to write a certain number of bytes of data to a stream. The call will block until one of the following conditions is true:

  • All of the data in the supplied basic_streambuf has been written.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the stream's write_some function.

Parameters

s

The stream to which the data is to be written. The type must support the SyncWriteStream concept.

b

The basic_streambuf object from which data will be written.

Return Value

The number of bytes transferred.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

This overload is equivalent to calling:

boost::asio::write(
    s, b,
    boost::asio::transfer_all());

Write all of the supplied data to a stream before returning.

template<
    typename SyncWriteStream,
    typename Allocator>
std::size_t write(
    SyncWriteStream & s,
    basic_streambuf< Allocator > & b,
    boost::system::error_code & ec);

This function is used to write a certain number of bytes of data to a stream. The call will block until one of the following conditions is true:

  • All of the data in the supplied basic_streambuf has been written.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the stream's write_some function.

Parameters

s

The stream to which the data is to be written. The type must support the SyncWriteStream concept.

b

The basic_streambuf object from which data will be written.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes transferred.

Remarks

This overload is equivalent to calling:

boost::asio::write(
    s, b,
    boost::asio::transfer_all(), ec);

Write a certain amount of data to a stream before returning.

template<
    typename SyncWriteStream,
    typename Allocator,
    typename CompletionCondition>
std::size_t write(
    SyncWriteStream & s,
    basic_streambuf< Allocator > & b,
    CompletionCondition completion_condition);

This function is used to write a certain number of bytes of data to a stream. The call will block until one of the following conditions is true:

  • All of the data in the supplied basic_streambuf has been written.
  • The completion_condition function object returns 0.

This operation is implemented in terms of zero or more calls to the stream's write_some function.

Parameters

s

The stream to which the data is to be written. The type must support the SyncWriteStream concept.

b

The basic_streambuf object from which data will be written.

completion_condition

The function object to be called to determine whether the write operation is complete. The signature of the function object must be:

std::size_t completion_condition(
  // Result of latest write_some operation.
  const boost::system::error_code& error,

  // Number of bytes transferred so far.
  std::size_t bytes_transferred
);

A return value of 0 indicates that the write operation is complete. A non-zero return value indicates the maximum number of bytes to be written on the next call to the stream's write_some function.

Return Value

The number of bytes transferred.

Exceptions

boost::system::system_error

Thrown on failure.

Write a certain amount of data to a stream before returning.

template<
    typename SyncWriteStream,
    typename Allocator,
    typename CompletionCondition>
std::size_t write(
    SyncWriteStream & s,
    basic_streambuf< Allocator > & b,
    CompletionCondition completion_condition,
    boost::system::error_code & ec);

This function is used to write a certain number of bytes of data to a stream. The call will block until one of the following conditions is true:

  • All of the data in the supplied basic_streambuf has been written.
  • The completion_condition function object returns 0.

This operation is implemented in terms of zero or more calls to the stream's write_some function.

Parameters

s

The stream to which the data is to be written. The type must support the SyncWriteStream concept.

b

The basic_streambuf object from which data will be written.

completion_condition

The function object to be called to determine whether the write operation is complete. The signature of the function object must be:

std::size_t completion_condition(
  // Result of latest write_some operation.
  const boost::system::error_code& error,

  // Number of bytes transferred so far.
  std::size_t bytes_transferred
);

A return value of 0 indicates that the write operation is complete. A non-zero return value indicates the maximum number of bytes to be written on the next call to the stream's write_some function.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes written. If an error occurs, returns the total number of bytes successfully transferred prior to the error.

Write a certain amount of data at a specified offset before returning.

template<
    typename SyncRandomAccessWriteDevice,
    typename ConstBufferSequence>
std::size_t write_at(
    SyncRandomAccessWriteDevice & d,
    uint64_t offset,
    const ConstBufferSequence & buffers);
  » more...

template<
    typename SyncRandomAccessWriteDevice,
    typename ConstBufferSequence>
std::size_t write_at(
    SyncRandomAccessWriteDevice & d,
    uint64_t offset,
    const ConstBufferSequence & buffers,
    boost::system::error_code & ec);
  » more...

template<
    typename SyncRandomAccessWriteDevice,
    typename ConstBufferSequence,
    typename CompletionCondition>
std::size_t write_at(
    SyncRandomAccessWriteDevice & d,
    uint64_t offset,
    const ConstBufferSequence & buffers,
    CompletionCondition completion_condition);
  » more...

template<
    typename SyncRandomAccessWriteDevice,
    typename ConstBufferSequence,
    typename CompletionCondition>
std::size_t write_at(
    SyncRandomAccessWriteDevice & d,
    uint64_t offset,
    const ConstBufferSequence & buffers,
    CompletionCondition completion_condition,
    boost::system::error_code & ec);
  » more...

template<
    typename SyncRandomAccessWriteDevice,
    typename Allocator>
std::size_t write_at(
    SyncRandomAccessWriteDevice & d,
    uint64_t offset,
    basic_streambuf< Allocator > & b);
  » more...

template<
    typename SyncRandomAccessWriteDevice,
    typename Allocator>
std::size_t write_at(
    SyncRandomAccessWriteDevice & d,
    uint64_t offset,
    basic_streambuf< Allocator > & b,
    boost::system::error_code & ec);
  » more...

template<
    typename SyncRandomAccessWriteDevice,
    typename Allocator,
    typename CompletionCondition>
std::size_t write_at(
    SyncRandomAccessWriteDevice & d,
    uint64_t offset,
    basic_streambuf< Allocator > & b,
    CompletionCondition completion_condition);
  » more...

template<
    typename SyncRandomAccessWriteDevice,
    typename Allocator,
    typename CompletionCondition>
std::size_t write_at(
    SyncRandomAccessWriteDevice & d,
    uint64_t offset,
    basic_streambuf< Allocator > & b,
    CompletionCondition completion_condition,
    boost::system::error_code & ec);
  » more...
Requirements

Header: boost/asio/write_at.hpp

Convenience header: boost/asio.hpp

Write all of the supplied data at the specified offset before returning.

template<
    typename SyncRandomAccessWriteDevice,
    typename ConstBufferSequence>
std::size_t write_at(
    SyncRandomAccessWriteDevice & d,
    uint64_t offset,
    const ConstBufferSequence & buffers);

This function is used to write a certain number of bytes of data to a random access device at a specified offset. The call will block until one of the following conditions is true:

  • All of the data in the supplied buffers has been written. That is, the bytes transferred is equal to the sum of the buffer sizes.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the device's write_some_at function.

Parameters

d

The device to which the data is to be written. The type must support the SyncRandomAccessWriteDevice concept.

offset

The offset at which the data will be written.

buffers

One or more buffers containing the data to be written. The sum of the buffer sizes indicates the maximum number of bytes to write to the device.

Return Value

The number of bytes transferred.

Exceptions

boost::system::system_error

Thrown on failure.

Example

To write a single data buffer use the buffer function as follows:

boost::asio::write_at(d, 42, boost::asio::buffer(data, size));

See the buffer documentation for information on writing multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Remarks

This overload is equivalent to calling:

boost::asio::write_at(
    d, offset, buffers,
    boost::asio::transfer_all());

Write all of the supplied data at the specified offset before returning.

template<
    typename SyncRandomAccessWriteDevice,
    typename ConstBufferSequence>
std::size_t write_at(
    SyncRandomAccessWriteDevice & d,
    uint64_t offset,
    const ConstBufferSequence & buffers,
    boost::system::error_code & ec);

This function is used to write a certain number of bytes of data to a random access device at a specified offset. The call will block until one of the following conditions is true:

  • All of the data in the supplied buffers has been written. That is, the bytes transferred is equal to the sum of the buffer sizes.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the device's write_some_at function.

Parameters

d

The device to which the data is to be written. The type must support the SyncRandomAccessWriteDevice concept.

offset

The offset at which the data will be written.

buffers

One or more buffers containing the data to be written. The sum of the buffer sizes indicates the maximum number of bytes to write to the device.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes transferred.

Example

To write a single data buffer use the buffer function as follows:

boost::asio::write_at(d, 42,
    boost::asio::buffer(data, size), ec);

See the buffer documentation for information on writing multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Remarks

This overload is equivalent to calling:

boost::asio::write_at(
    d, offset, buffers,
    boost::asio::transfer_all(), ec);

Write a certain amount of data at a specified offset before returning.

template<
    typename SyncRandomAccessWriteDevice,
    typename ConstBufferSequence,
    typename CompletionCondition>
std::size_t write_at(
    SyncRandomAccessWriteDevice & d,
    uint64_t offset,
    const ConstBufferSequence & buffers,
    CompletionCondition completion_condition);

This function is used to write a certain number of bytes of data to a random access device at a specified offset. The call will block until one of the following conditions is true:

  • All of the data in the supplied buffers has been written. That is, the bytes transferred is equal to the sum of the buffer sizes.
  • The completion_condition function object returns 0.

This operation is implemented in terms of zero or more calls to the device's write_some_at function.

Parameters

d

The device to which the data is to be written. The type must support the SyncRandomAccessWriteDevice concept.

offset

The offset at which the data will be written.

buffers

One or more buffers containing the data to be written. The sum of the buffer sizes indicates the maximum number of bytes to write to the device.

completion_condition

The function object to be called to determine whether the write operation is complete. The signature of the function object must be:

std::size_t completion_condition(
  // Result of latest write_some_at operation.
  const boost::system::error_code& error,

  // Number of bytes transferred so far.
  std::size_t bytes_transferred
);

A return value of 0 indicates that the write operation is complete. A non-zero return value indicates the maximum number of bytes to be written on the next call to the device's write_some_at function.

Return Value

The number of bytes transferred.

Exceptions

boost::system::system_error

Thrown on failure.

Example

To write a single data buffer use the buffer function as follows:

boost::asio::write_at(d, 42, boost::asio::buffer(data, size),
    boost::asio::transfer_at_least(32));

See the buffer documentation for information on writing multiple buffers in one go, and how to use it with arrays, boost::array or std::vector.

Write a certain amount of data at a specified offset before returning.

template<
    typename SyncRandomAccessWriteDevice,
    typename ConstBufferSequence,
    typename CompletionCondition>
std::size_t write_at(
    SyncRandomAccessWriteDevice & d,
    uint64_t offset,
    const ConstBufferSequence & buffers,
    CompletionCondition completion_condition,
    boost::system::error_code & ec);

This function is used to write a certain number of bytes of data to a random access device at a specified offset. The call will block until one of the following conditions is true:

  • All of the data in the supplied buffers has been written. That is, the bytes transferred is equal to the sum of the buffer sizes.
  • The completion_condition function object returns 0.

This operation is implemented in terms of zero or more calls to the device's write_some_at function.

Parameters

d

The device to which the data is to be written. The type must support the SyncRandomAccessWriteDevice concept.

offset

The offset at which the data will be written.

buffers

One or more buffers containing the data to be written. The sum of the buffer sizes indicates the maximum number of bytes to write to the device.

completion_condition

The function object to be called to determine whether the write operation is complete. The signature of the function object must be:

std::size_t completion_condition(
  // Result of latest write_some_at operation.
  const boost::system::error_code& error,

  // Number of bytes transferred so far.
  std::size_t bytes_transferred
);

A return value of 0 indicates that the write operation is complete. A non-zero return value indicates the maximum number of bytes to be written on the next call to the device's write_some_at function.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes written. If an error occurs, returns the total number of bytes successfully transferred prior to the error.

Write all of the supplied data at the specified offset before returning.

template<
    typename SyncRandomAccessWriteDevice,
    typename Allocator>
std::size_t write_at(
    SyncRandomAccessWriteDevice & d,
    uint64_t offset,
    basic_streambuf< Allocator > & b);

This function is used to write a certain number of bytes of data to a random access device at a specified offset. The call will block until one of the following conditions is true:

  • All of the data in the supplied basic_streambuf has been written.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the device's write_some_at function.

Parameters

d

The device to which the data is to be written. The type must support the SyncRandomAccessWriteDevice concept.

offset

The offset at which the data will be written.

b

The basic_streambuf object from which data will be written.

Return Value

The number of bytes transferred.

Exceptions

boost::system::system_error

Thrown on failure.

Remarks

This overload is equivalent to calling:

boost::asio::write_at(
    d, 42, b,
    boost::asio::transfer_all());

Write all of the supplied data at the specified offset before returning.

template<
    typename SyncRandomAccessWriteDevice,
    typename Allocator>
std::size_t write_at(
    SyncRandomAccessWriteDevice & d,
    uint64_t offset,
    basic_streambuf< Allocator > & b,
    boost::system::error_code & ec);

This function is used to write a certain number of bytes of data to a random access device at a specified offset. The call will block until one of the following conditions is true:

  • All of the data in the supplied basic_streambuf has been written.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the device's write_some_at function.

Parameters

d

The device to which the data is to be written. The type must support the SyncRandomAccessWriteDevice concept.

offset

The offset at which the data will be written.

b

The basic_streambuf object from which data will be written.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes transferred.

Remarks

This overload is equivalent to calling:

boost::asio::write_at(
    d, 42, b,
    boost::asio::transfer_all(), ec);

Write a certain amount of data at a specified offset before returning.

template<
    typename SyncRandomAccessWriteDevice,
    typename Allocator,
    typename CompletionCondition>
std::size_t write_at(
    SyncRandomAccessWriteDevice & d,
    uint64_t offset,
    basic_streambuf< Allocator > & b,
    CompletionCondition completion_condition);

This function is used to write a certain number of bytes of data to a random access device at a specified offset. The call will block until one of the following conditions is true:

  • All of the data in the supplied basic_streambuf has been written.
  • The completion_condition function object returns 0.

This operation is implemented in terms of zero or more calls to the device's write_some_at function.

Parameters

d

The device to which the data is to be written. The type must support the SyncRandomAccessWriteDevice concept.

offset

The offset at which the data will be written.

b

The basic_streambuf object from which data will be written.

completion_condition

The function object to be called to determine whether the write operation is complete. The signature of the function object must be:

std::size_t completion_condition(
  // Result of latest write_some_at operation.
  const boost::system::error_code& error,

  // Number of bytes transferred so far.
  std::size_t bytes_transferred
);

A return value of 0 indicates that the write operation is complete. A non-zero return value indicates the maximum number of bytes to be written on the next call to the device's write_some_at function.

Return Value

The number of bytes transferred.

Exceptions

boost::system::system_error

Thrown on failure.

Write a certain amount of data at a specified offset before returning.

template<
    typename SyncRandomAccessWriteDevice,
    typename Allocator,
    typename CompletionCondition>
std::size_t write_at(
    SyncRandomAccessWriteDevice & d,
    uint64_t offset,
    basic_streambuf< Allocator > & b,
    CompletionCondition completion_condition,
    boost::system::error_code & ec);

This function is used to write a certain number of bytes of data to a random access device at a specified offset. The call will block until one of the following conditions is true:

  • All of the data in the supplied basic_streambuf has been written.
  • The completion_condition function object returns 0.

This operation is implemented in terms of zero or more calls to the device's write_some_at function.

Parameters

d

The device to which the data is to be written. The type must support the SyncRandomAccessWriteDevice concept.

offset

The offset at which the data will be written.

b

The basic_streambuf object from which data will be written.

completion_condition

The function object to be called to determine whether the write operation is complete. The signature of the function object must be:

std::size_t completion_condition(
  // Result of latest write_some_at operation.
  const boost::system::error_code& error,

  // Number of bytes transferred so far.
  std::size_t bytes_transferred
);

A return value of 0 indicates that the write operation is complete. A non-zero return value indicates the maximum number of bytes to be written on the next call to the device's write_some_at function.

ec

Set to indicate what error occurred, if any.

Return Value

The number of bytes written. If an error occurs, returns the total number of bytes successfully transferred prior to the error.

Context object that represents the currently executing coroutine.

typedef basic_yield_context< unspecified > yield_context;
Types

Name

Description

callee_type

The coroutine callee type, used by the implementation.

caller_type

The coroutine caller type, used by the implementation.

Member Functions

Name

Description

basic_yield_context

Construct a yield context to represent the specified coroutine.

operator[]

Return a yield context that sets the specified error_code.

The basic_yield_context class is used to represent the currently executing stackful coroutine. A basic_yield_context may be passed as a handler to an asynchronous operation. For example:

template <typename Handler>
void my_coroutine(basic_yield_context<Handler> yield)
{
  ...
  std::size_t n = my_socket.async_read_some(buffer, yield);
  ...
}

The initiating function (async_read_some in the above example) suspends the current coroutine. The coroutine is resumed when the asynchronous operation completes, and the result of the operation is returned.

Requirements

Header: boost/asio/spawn.hpp

Convenience header: None

template<>
struct boost::system::is_error_code_enum< boost::asio::error::addrinfo_errors >
Data Members

Name

Description

value

Requirements

Header: boost/asio/error.hpp

Convenience header: boost/asio.hpp

template<>
struct boost::system::is_error_code_enum< boost::asio::error::basic_errors >
Data Members

Name

Description

value

Requirements

Header: boost/asio/error.hpp

Convenience header: boost/asio.hpp

template<>
struct boost::system::is_error_code_enum< boost::asio::error::misc_errors >
Data Members

Name

Description

value

Requirements

Header: boost/asio/error.hpp

Convenience header: boost/asio.hpp

template<>
struct boost::system::is_error_code_enum< boost::asio::error::netdb_errors >
Data Members

Name

Description

value

Requirements

Header: boost/asio/error.hpp

Convenience header: boost/asio.hpp

template<>
struct boost::system::is_error_code_enum< boost::asio::error::ssl_errors >
Data Members

Name

Description

value

Requirements

Header: boost/asio/ssl/error.hpp

Convenience header: boost/asio/ssl.hpp

template<>
struct boost::system::is_error_code_enum< boost::asio::ssl::error::stream_errors >
Data Members

Name

Description

value

Requirements

Header: boost/asio/ssl/error.hpp

Convenience header: boost/asio/ssl.hpp


PrevUpHomeNext