mirror of
https://github.com/boostorg/asio.git
synced 2026-01-28 06:42:08 +00:00
------------------------------------------------------------------------
r84301 | chris_kohlhoff | 2013-05-17 07:34:54 +1000 (Fri, 17 May 2013) | 2 lines
Enable handler type requirements static_assert on clang.
------------------------------------------------------------------------
r84308 | chris_kohlhoff | 2013-05-17 09:26:04 +1000 (Fri, 17 May 2013) | 3 lines
Add new traits classes, handler_type and async_result, that allow
the customisation of the return type of an initiating function.
------------------------------------------------------------------------
r84311 | chris_kohlhoff | 2013-05-17 11:38:47 +1000 (Fri, 17 May 2013) | 81 lines
Add the asio::spawn() function, a high-level wrapper for running
stackful coroutines. It is based on the Boost.Coroutine library.
Here is an example of its use:
asio::spawn(my_strand, do_echo);
// ...
void do_echo(asio::yield_context yield)
{
try
{
char data[128];
for (;;)
{
std::size_t length =
my_socket.async_read_some(
asio::buffer(data), yield);
asio::async_write(my_socket,
asio::buffer(data, length), yield);
}
}
catch (std::exception& e)
{
// ...
}
}
The first argument to asio::spawn() may be a strand, io_service or
completion handler. This argument determines the context in which the
coroutine is permitted to execute. For example, a server's per-client
object may consist of multiple coroutines; they should all run on the
same strand so that no explicit synchronisation is required.
The second argument is a function object with signature (**):
void coroutine(asio::yield_context yield);
that specifies the code to be run as part of the coroutine. The
parameter yield may be passed to an asynchronous operation in place of
the completion handler, as in:
std::size_t length =
my_socket.async_read_some(
asio::buffer(data), yield);
This starts the asynchronous operation and suspends the coroutine. The
coroutine will be resumed automatically when the asynchronous operation
completes.
Where a completion handler signature has the form:
void handler(error_code ec, result_type result);
the initiating function returns the result_type. In the async_read_some
example above, this is std::size_t. If the asynchronous operation fails,
the error_code is converted into a system_error exception and thrown.
Where a completion handler signature has the form:
void handler(error_code ec);
the initiating function returns void. As above, an error is passed back
to the coroutine as a system_error exception.
To collect the error_code from an operation, rather than have it throw
an exception, associate the output variable with the yield_context as
follows:
error_code ec;
std::size_t length =
my_socket.async_read_some(
asio::buffer(data), yield[ec]);
**Note: if asio::spawn() is used with a custom completion handler of
type Handler, the function object signature is actually:
void coroutine(asio::basic_yield_context<Handler> yield);
------------------------------------------------------------------------
r84312 | chris_kohlhoff | 2013-05-17 12:25:10 +1000 (Fri, 17 May 2013) | 4 lines
Move existing examples into a C++03-specific directory, and add a new
directory for C++11-specific examples. A limited subset of the C++03
examples have been converted to their C++11 equivalents.
------------------------------------------------------------------------
r84313 | chris_kohlhoff | 2013-05-17 12:35:08 +1000 (Fri, 17 May 2013) | 26 lines
Add the asio::use_future special value, which adds first-class support
for returning a C++11 std::future from an asynchronous operation's
initiating function.
To use asio::use_future, pass it to an asynchronous operation instead of
a normal completion handler. For example:
std::future<std::size_t> length =
my_socket.async_read_some(my_buffer, asio::use_future);
Where a completion 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 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 completion handler signature has the form:
void handler(error_code ec);
the initiating function returns std::future<void>. As above, an error
is passed back in the future as a system_error exception.
------------------------------------------------------------------------
r84314 | chris_kohlhoff | 2013-05-17 13:07:51 +1000 (Fri, 17 May 2013) | 27 lines
Add a new handler hook called asio_handler_is_continuation.
Asynchronous operations may represent a continuation of the asynchronous
control flow associated with the current handler. Asio's implementation
can use this knowledge to optimise scheduling of the handler.
The asio_handler_is_continuation hook returns true to indicate whether a
completion handler represents a continuation of the current call
context. The default implementation of the hook returns false, and
applications may customise the hook when necessary. The hook has already
been customised within Asio to return true for the following cases:
- Handlers returned by strand.wrap(), when the corresponding
asynchronous operation is being initiated from within the strand.
- The internal handlers used to implement the asio::spawn() function's
stackful coroutines.
- When an intermediate handler of a composed operation (e.g.
asio::async_read(), asio::async_write(), asio::async_connect(),
ssl::stream<>, etc.) starts a new asynchronous operation due to the
composed operation not being complete.
To support this optimisation, a new running_in_this_thread() member
function has been added to the io_service::strand class. This function
returns true when called from within a strand.
------------------------------------------------------------------------
r84315 | chris_kohlhoff | 2013-05-17 20:06:50 +1000 (Fri, 17 May 2013) | 3 lines
Partially decouple Asio from other boost components via an extra level
of indirection.
------------------------------------------------------------------------
r84316 | chris_kohlhoff | 2013-05-17 20:15:21 +1000 (Fri, 17 May 2013) | 2 lines
Minor cleanup.
------------------------------------------------------------------------
r84319 | chris_kohlhoff | 2013-05-17 20:52:08 +1000 (Fri, 17 May 2013) | 9 lines
Support handshake with re-use of data already read from the wire.
Add new overloads of the SSL stream's handshake() and async_handshake()
functions, that accepts a ConstBufferSequence to be used as initial
input to the ssl engine for the handshake procedure.
Thanks go to Nick Jones <nick dot fa dot jones at gmail dot com>, on
whose work this commit is partially based.
------------------------------------------------------------------------
r84320 | chris_kohlhoff | 2013-05-17 20:57:02 +1000 (Fri, 17 May 2013) | 6 lines
Support for creation of TLSv1.1 and TLSv1.2 contexts.
Thanks go to Alvin Cheung <alvin dot cheung at alumni dot ust dot hk>
and Nick Jones <nick dot fa dot jones at gmail dot com>, on whose work
this is based.
------------------------------------------------------------------------
r84322 | chris_kohlhoff | 2013-05-17 21:00:49 +1000 (Fri, 17 May 2013) | 5 lines
Add set_verify_depth function to SSL context and stream.
Thanks go to Nick Jones <nick dot fa dot jones at gmail dot com>, on
whose work this commit is based.
------------------------------------------------------------------------
r84325 | chris_kohlhoff | 2013-05-17 21:04:11 +1000 (Fri, 17 May 2013) | 9 lines
Allow loading of SSL certificate and key data from memory buffers.
Added new buffer-based interfaces:
add_certificate_authority, use_certificate, use_certificate_chain,
use_private_key, use_rsa_private_key, use_tmp_dh.
Thanks go to Nick Jones <nick dot fa dot jones at gmail dot com>, on
whose work this commit is based.
------------------------------------------------------------------------
r84345 | chris_kohlhoff | 2013-05-18 21:24:59 +1000 (Sat, 18 May 2013) | 2 lines
Update copyright notices.
------------------------------------------------------------------------
r84346 | chris_kohlhoff | 2013-05-18 21:54:59 +1000 (Sat, 18 May 2013) | 3 lines
Remove the stackless coroutine class and macros from the HTTP server 4
example, and instead make them a part of Asio's documented interface.
------------------------------------------------------------------------
r84347 | chris_kohlhoff | 2013-05-18 22:01:59 +1000 (Sat, 18 May 2013) | 4 lines
Fix basic_waitable_timer's underlying implementation so that it can
handle any time_point value without overflowing the intermediate
duration objects.
------------------------------------------------------------------------
r84348 | chris_kohlhoff | 2013-05-18 22:07:00 +1000 (Sat, 18 May 2013) | 3 lines
Fix a problem with lost thread wakeups that can occur when making
concurrent calls to run() and poll() on the same io_service object.
------------------------------------------------------------------------
r84349 | chris_kohlhoff | 2013-05-18 22:13:17 +1000 (Sat, 18 May 2013) | 3 lines
Fix implementation of asynchronous connect operation so that it can cope
with spurious readiness notifications from the reactor.
------------------------------------------------------------------------
r84361 | chris_kohlhoff | 2013-05-19 07:56:31 +1000 (Sun, 19 May 2013) | 1 line
Remove some trailing spaces and fix another copyright notice.
------------------------------------------------------------------------
r84363 | chris_kohlhoff | 2013-05-19 14:55:11 +1000 (Sun, 19 May 2013) | 53 lines
Add generic socket protocols and converting move constructors.
Four new protocol classes have been added:
- asio::generic::datagram_protocol
- asio::generic::raw_protocol
- asio::generic::seq_packet_protocol
- asio::generic::stream_protocol
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.
A new endpoint class template, asio::generic::basic_endpoint, has been
added to support these new protocol classes. This endpoint can hold any
other endpoint type, provided its native representation fits into a
sockaddr_storage object.
When using C++11, it is now 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 socket1(io_service);
...
Protocol2::socket socket2(std::move(socket1));
For example, one possible conversion is from a TCP socket to a generic
stream-oriented socket:
asio::ip::tcp::socket socket1(io_service);
...
asio::generic::stream_protocol::socket socket2(std::move(socket1));
The conversion is also available for move-assignment. Note that these
conversions are not limited to the newly added 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.
As a convenience, the socket acceptor's accept() and async_accept()
functions have been changed so that they can directly accept into a
different protocol's socket type, provided the protocol conversion is
valid. For example, the following is now possible:
asio::ip::tcp::acceptor acceptor(io_service);
...
asio::generic::stream_protocol::socket socket1(io_service);
acceptor.accept(socket1);
[SVN r84388]
307 lines
8.9 KiB
C++
307 lines
8.9 KiB
C++
//
|
|
// async_tcp_client.cpp
|
|
// ~~~~~~~~~~~~~~~~~~~~
|
|
//
|
|
// Copyright (c) 2003-2013 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
|
//
|
|
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
|
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
|
//
|
|
|
|
#include <boost/asio/deadline_timer.hpp>
|
|
#include <boost/asio/io_service.hpp>
|
|
#include <boost/asio/ip/tcp.hpp>
|
|
#include <boost/asio/read_until.hpp>
|
|
#include <boost/asio/streambuf.hpp>
|
|
#include <boost/asio/write.hpp>
|
|
#include <boost/bind.hpp>
|
|
#include <iostream>
|
|
|
|
using boost::asio::deadline_timer;
|
|
using boost::asio::ip::tcp;
|
|
|
|
//
|
|
// This class manages socket timeouts by applying the concept of a deadline.
|
|
// Some asynchronous operations are given deadlines by which they must complete.
|
|
// Deadlines are enforced by an "actor" that persists for the lifetime of the
|
|
// client object:
|
|
//
|
|
// +----------------+
|
|
// | |
|
|
// | check_deadline |<---+
|
|
// | | |
|
|
// +----------------+ | async_wait()
|
|
// | |
|
|
// +---------+
|
|
//
|
|
// If the deadline actor determines that the deadline has expired, the socket
|
|
// is closed and any outstanding operations are consequently cancelled.
|
|
//
|
|
// Connection establishment involves trying each endpoint in turn until a
|
|
// connection is successful, or the available endpoints are exhausted. If the
|
|
// deadline actor closes the socket, the connect actor is woken up and moves to
|
|
// the next endpoint.
|
|
//
|
|
// +---------------+
|
|
// | |
|
|
// | start_connect |<---+
|
|
// | | |
|
|
// +---------------+ |
|
|
// | |
|
|
// async_- | +----------------+
|
|
// connect() | | |
|
|
// +--->| handle_connect |
|
|
// | |
|
|
// +----------------+
|
|
// :
|
|
// Once a connection is :
|
|
// made, the connect :
|
|
// actor forks in two - :
|
|
// :
|
|
// an actor for reading : and an actor for
|
|
// inbound messages: : sending heartbeats:
|
|
// :
|
|
// +------------+ : +-------------+
|
|
// | |<- - - - -+- - - - ->| |
|
|
// | start_read | | start_write |<---+
|
|
// | |<---+ | | |
|
|
// +------------+ | +-------------+ | async_wait()
|
|
// | | | |
|
|
// async_- | +-------------+ async_- | +--------------+
|
|
// read_- | | | write() | | |
|
|
// until() +--->| handle_read | +--->| handle_write |
|
|
// | | | |
|
|
// +-------------+ +--------------+
|
|
//
|
|
// The input actor reads messages from the socket, where messages are delimited
|
|
// by the newline character. The deadline for a complete message is 30 seconds.
|
|
//
|
|
// The heartbeat actor sends a heartbeat (a message that consists of a single
|
|
// newline character) every 10 seconds. In this example, no deadline is applied
|
|
// message sending.
|
|
//
|
|
class client
|
|
{
|
|
public:
|
|
client(boost::asio::io_service& io_service)
|
|
: stopped_(false),
|
|
socket_(io_service),
|
|
deadline_(io_service),
|
|
heartbeat_timer_(io_service)
|
|
{
|
|
}
|
|
|
|
// Called by the user of the client class to initiate the connection process.
|
|
// The endpoint iterator will have been obtained using a tcp::resolver.
|
|
void start(tcp::resolver::iterator endpoint_iter)
|
|
{
|
|
// Start the connect actor.
|
|
start_connect(endpoint_iter);
|
|
|
|
// Start the deadline actor. You will note that we're not setting any
|
|
// particular deadline here. Instead, the connect and input actors will
|
|
// update the deadline prior to each asynchronous operation.
|
|
deadline_.async_wait(boost::bind(&client::check_deadline, this));
|
|
}
|
|
|
|
// This function terminates all the actors to shut down the connection. It
|
|
// may be called by the user of the client class, or by the class itself in
|
|
// response to graceful termination or an unrecoverable error.
|
|
void stop()
|
|
{
|
|
stopped_ = true;
|
|
boost::system::error_code ignored_ec;
|
|
socket_.close(ignored_ec);
|
|
deadline_.cancel();
|
|
heartbeat_timer_.cancel();
|
|
}
|
|
|
|
private:
|
|
void start_connect(tcp::resolver::iterator endpoint_iter)
|
|
{
|
|
if (endpoint_iter != tcp::resolver::iterator())
|
|
{
|
|
std::cout << "Trying " << endpoint_iter->endpoint() << "...\n";
|
|
|
|
// Set a deadline for the connect operation.
|
|
deadline_.expires_from_now(boost::posix_time::seconds(60));
|
|
|
|
// Start the asynchronous connect operation.
|
|
socket_.async_connect(endpoint_iter->endpoint(),
|
|
boost::bind(&client::handle_connect,
|
|
this, _1, endpoint_iter));
|
|
}
|
|
else
|
|
{
|
|
// There are no more endpoints to try. Shut down the client.
|
|
stop();
|
|
}
|
|
}
|
|
|
|
void handle_connect(const boost::system::error_code& ec,
|
|
tcp::resolver::iterator endpoint_iter)
|
|
{
|
|
if (stopped_)
|
|
return;
|
|
|
|
// The async_connect() function automatically opens the socket at the start
|
|
// of the asynchronous operation. If the socket is closed at this time then
|
|
// the timeout handler must have run first.
|
|
if (!socket_.is_open())
|
|
{
|
|
std::cout << "Connect timed out\n";
|
|
|
|
// Try the next available endpoint.
|
|
start_connect(++endpoint_iter);
|
|
}
|
|
|
|
// Check if the connect operation failed before the deadline expired.
|
|
else if (ec)
|
|
{
|
|
std::cout << "Connect error: " << ec.message() << "\n";
|
|
|
|
// We need to close the socket used in the previous connection attempt
|
|
// before starting a new one.
|
|
socket_.close();
|
|
|
|
// Try the next available endpoint.
|
|
start_connect(++endpoint_iter);
|
|
}
|
|
|
|
// Otherwise we have successfully established a connection.
|
|
else
|
|
{
|
|
std::cout << "Connected to " << endpoint_iter->endpoint() << "\n";
|
|
|
|
// Start the input actor.
|
|
start_read();
|
|
|
|
// Start the heartbeat actor.
|
|
start_write();
|
|
}
|
|
}
|
|
|
|
void start_read()
|
|
{
|
|
// Set a deadline for the read operation.
|
|
deadline_.expires_from_now(boost::posix_time::seconds(30));
|
|
|
|
// Start an asynchronous operation to read a newline-delimited message.
|
|
boost::asio::async_read_until(socket_, input_buffer_, '\n',
|
|
boost::bind(&client::handle_read, this, _1));
|
|
}
|
|
|
|
void handle_read(const boost::system::error_code& ec)
|
|
{
|
|
if (stopped_)
|
|
return;
|
|
|
|
if (!ec)
|
|
{
|
|
// Extract the newline-delimited message from the buffer.
|
|
std::string line;
|
|
std::istream is(&input_buffer_);
|
|
std::getline(is, line);
|
|
|
|
// Empty messages are heartbeats and so ignored.
|
|
if (!line.empty())
|
|
{
|
|
std::cout << "Received: " << line << "\n";
|
|
}
|
|
|
|
start_read();
|
|
}
|
|
else
|
|
{
|
|
std::cout << "Error on receive: " << ec.message() << "\n";
|
|
|
|
stop();
|
|
}
|
|
}
|
|
|
|
void start_write()
|
|
{
|
|
if (stopped_)
|
|
return;
|
|
|
|
// Start an asynchronous operation to send a heartbeat message.
|
|
boost::asio::async_write(socket_, boost::asio::buffer("\n", 1),
|
|
boost::bind(&client::handle_write, this, _1));
|
|
}
|
|
|
|
void handle_write(const boost::system::error_code& ec)
|
|
{
|
|
if (stopped_)
|
|
return;
|
|
|
|
if (!ec)
|
|
{
|
|
// Wait 10 seconds before sending the next heartbeat.
|
|
heartbeat_timer_.expires_from_now(boost::posix_time::seconds(10));
|
|
heartbeat_timer_.async_wait(boost::bind(&client::start_write, this));
|
|
}
|
|
else
|
|
{
|
|
std::cout << "Error on heartbeat: " << ec.message() << "\n";
|
|
|
|
stop();
|
|
}
|
|
}
|
|
|
|
void check_deadline()
|
|
{
|
|
if (stopped_)
|
|
return;
|
|
|
|
// Check whether the deadline has passed. We compare the deadline against
|
|
// the current time since a new asynchronous operation may have moved the
|
|
// deadline before this actor had a chance to run.
|
|
if (deadline_.expires_at() <= deadline_timer::traits_type::now())
|
|
{
|
|
// The deadline has passed. The socket is closed so that any outstanding
|
|
// asynchronous operations are cancelled.
|
|
socket_.close();
|
|
|
|
// There is no longer an active deadline. The expiry is set to positive
|
|
// infinity so that the actor takes no action until a new deadline is set.
|
|
deadline_.expires_at(boost::posix_time::pos_infin);
|
|
}
|
|
|
|
// Put the actor back to sleep.
|
|
deadline_.async_wait(boost::bind(&client::check_deadline, this));
|
|
}
|
|
|
|
private:
|
|
bool stopped_;
|
|
tcp::socket socket_;
|
|
boost::asio::streambuf input_buffer_;
|
|
deadline_timer deadline_;
|
|
deadline_timer heartbeat_timer_;
|
|
};
|
|
|
|
int main(int argc, char* argv[])
|
|
{
|
|
try
|
|
{
|
|
if (argc != 3)
|
|
{
|
|
std::cerr << "Usage: client <host> <port>\n";
|
|
return 1;
|
|
}
|
|
|
|
boost::asio::io_service io_service;
|
|
tcp::resolver r(io_service);
|
|
client c(io_service);
|
|
|
|
c.start(r.resolve(tcp::resolver::query(argv[1], argv[2])));
|
|
|
|
io_service.run();
|
|
}
|
|
catch (std::exception& e)
|
|
{
|
|
std::cerr << "Exception: " << e.what() << "\n";
|
|
}
|
|
|
|
return 0;
|
|
}
|