asio C++ library

PrevUpHomeNext

Support for Other Protocols

Support for other socket protocols (such as Bluetooth or IRCOMM sockets) can be added by implementing the protocol type requirements. However, in many cases these protocols may also be used with Asio's generic protocol support. For this, Asio provides the following four classes:

These classes implement the protocol type requirements, but allow the user to specify the address family (e.g. AF_INET) and protocol type (e.g. IPPROTO_TCP) at runtime. For example:

asio::generic::stream_protocol::socket my_socket(my_io_context);
my_socket.open(asio::generic::stream_protocol(AF_INET, IPPROTO_TCP));
...

An endpoint class template, asio::generic::basic_endpoint, is included to support these protocol classes. This endpoint can hold any other endpoint type, provided its native representation fits into a sockaddr_storage object. This class will also convert from other types that implement the endpoint type requirements:

asio::ip::tcp::endpoint my_endpoint1 = ...;
asio::generic::stream_protocol::endpoint my_endpoint2(my_endpoint1);

The conversion is implicit, so as to support the following use cases:

asio::generic::stream_protocol::socket my_socket(my_io_context);
asio::ip::tcp::endpoint my_endpoint = ...;
my_socket.connect(my_endpoint);
C++11 Move Construction

When using C++11, it is possible to perform move construction from a socket (or acceptor) object to convert to the more generic protocol's socket (or acceptor) type. If the protocol conversion is valid:

Protocol1 p1 = ...;
Protocol2 p2(p1);

then the corresponding socket conversion is allowed:

Protocol1::socket my_socket1(my_io_context);
...
Protocol2::socket my_socket2(std::move(my_socket1));

For example, one possible conversion is from a TCP socket to a generic stream-oriented socket:

asio::ip::tcp::socket my_socket1(my_io_context);
...
asio::generic::stream_protocol::socket my_socket2(std::move(my_socket1));

These conversions are also available for move-assignment.

These conversions are not limited to the above generic protocol classes. User-defined protocols may take advantage of this feature by similarly ensuring the conversion from Protocol1 to Protocol2 is valid, as above.

Accepting Generic Sockets

As a convenience, a socket acceptor's accept() and async_accept() functions can directly accept into a different protocol's socket type, provided the corresponding protocol conversion is valid. For example, the following is supported because the protocol asio::ip::tcp is convertible to asio::generic::stream_protocol:

asio::ip::tcp::acceptor my_acceptor(my_io_context);
...
asio::generic::stream_protocol::socket my_socket(my_io_context);
my_acceptor.accept(my_socket);
See Also

generic::datagram_protocol, generic::raw_protocol, generic::seq_packet_protocol, generic::stream_protocol, protocol type requirements.


PrevUpHomeNext