Unnamed: 0
int64 0
0
| repo_id
stringlengths 5
186
| file_path
stringlengths 15
223
| content
stringlengths 1
32.8M
⌀ |
---|---|---|---|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/multicast/sender.cpp | //
// sender.cpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <iostream>
#include <sstream>
#include <string>
#include "asio.hpp"
constexpr short multicast_port = 30001;
constexpr int max_message_count = 10;
class sender
{
public:
sender(asio::io_context& io_context,
const asio::ip::address& multicast_address)
: endpoint_(multicast_address, multicast_port),
socket_(io_context, endpoint_.protocol()),
timer_(io_context),
message_count_(0)
{
do_send();
}
private:
void do_send()
{
std::ostringstream os;
os << "Message " << message_count_++;
message_ = os.str();
socket_.async_send_to(
asio::buffer(message_), endpoint_,
[this](std::error_code ec, std::size_t /*length*/)
{
if (!ec && message_count_ < max_message_count)
do_timeout();
});
}
void do_timeout()
{
timer_.expires_after(std::chrono::seconds(1));
timer_.async_wait(
[this](std::error_code ec)
{
if (!ec)
do_send();
});
}
private:
asio::ip::udp::endpoint endpoint_;
asio::ip::udp::socket socket_;
asio::steady_timer timer_;
int message_count_;
std::string message_;
};
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: sender <multicast_address>\n";
std::cerr << " For IPv4, try:\n";
std::cerr << " sender 239.255.0.1\n";
std::cerr << " For IPv6, try:\n";
std::cerr << " sender ff31::8000:1234\n";
return 1;
}
asio::io_context io_context;
sender s(io_context, asio::ip::make_address(argv[1]));
io_context.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/windows/transmit_file.cpp | //
// transmit_file.cpp
// ~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <ctime>
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include "asio.hpp"
#if defined(ASIO_HAS_WINDOWS_OVERLAPPED_PTR)
using asio::ip::tcp;
using asio::windows::overlapped_ptr;
using asio::windows::random_access_handle;
typedef asio::basic_stream_socket<tcp,
asio::io_context::executor_type> tcp_socket;
typedef asio::basic_socket_acceptor<tcp,
asio::io_context::executor_type> tcp_acceptor;
// A wrapper for the TransmitFile overlapped I/O operation.
template <typename Handler>
void transmit_file(tcp_socket& socket,
random_access_handle& file, Handler handler)
{
// Construct an OVERLAPPED-derived object to contain the handler.
overlapped_ptr overlapped(socket.get_executor().context(), handler);
// Initiate the TransmitFile operation.
BOOL ok = ::TransmitFile(socket.native_handle(),
file.native_handle(), 0, 0, overlapped.get(), 0, 0);
DWORD last_error = ::GetLastError();
// Check if the operation completed immediately.
if (!ok && last_error != ERROR_IO_PENDING)
{
// The operation completed immediately, so a completion notification needs
// to be posted. When complete() is called, ownership of the OVERLAPPED-
// derived object passes to the io_context.
std::error_code ec(last_error,
asio::error::get_system_category());
overlapped.complete(ec, 0);
}
else
{
// The operation was successfully initiated, so ownership of the
// OVERLAPPED-derived object has passed to the io_context.
overlapped.release();
}
}
class connection
: public std::enable_shared_from_this<connection>
{
public:
typedef std::shared_ptr<connection> pointer;
static pointer create(asio::io_context& io_context,
const std::string& filename)
{
return pointer(new connection(io_context, filename));
}
tcp_socket& socket()
{
return socket_;
}
void start()
{
std::error_code ec;
file_.assign(::CreateFile(filename_.c_str(), GENERIC_READ, 0, 0,
OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, 0), ec);
if (file_.is_open())
{
transmit_file(socket_, file_,
std::bind(&connection::handle_write, shared_from_this(),
asio::placeholders::error,
asio::placeholders::bytes_transferred));
}
}
private:
connection(asio::io_context& io_context, const std::string& filename)
: socket_(io_context),
filename_(filename),
file_(io_context)
{
}
void handle_write(const std::error_code& /*error*/,
size_t /*bytes_transferred*/)
{
std::error_code ignored_ec;
socket_.shutdown(tcp_socket::shutdown_both, ignored_ec);
}
tcp_socket socket_;
std::string filename_;
random_access_handle file_;
};
class server
{
public:
server(asio::io_context& io_context,
unsigned short port, const std::string& filename)
: acceptor_(io_context, tcp::endpoint(tcp::v4(), port)),
filename_(filename)
{
start_accept();
}
private:
void start_accept()
{
connection::pointer new_connection =
connection::create(acceptor_.get_executor().context(), filename_);
acceptor_.async_accept(new_connection->socket(),
std::bind(&server::handle_accept, this, new_connection,
asio::placeholders::error));
}
void handle_accept(connection::pointer new_connection,
const std::error_code& error)
{
if (!error)
{
new_connection->start();
}
start_accept();
}
tcp_acceptor acceptor_;
std::string filename_;
};
int main(int argc, char* argv[])
{
try
{
if (argc != 3)
{
std::cerr << "Usage: transmit_file <port> <filename>\n";
return 1;
}
asio::io_context io_context;
using namespace std; // For atoi.
server s(io_context, atoi(argv[1]), argv[2]);
io_context.run();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
#else // defined(ASIO_HAS_WINDOWS_OVERLAPPED_PTR)
# error Overlapped I/O not available on this platform
#endif // defined(ASIO_HAS_WINDOWS_OVERLAPPED_PTR)
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/icmp/ipv4_header.hpp | //
// ipv4_header.hpp
// ~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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)
//
#ifndef IPV4_HEADER_HPP
#define IPV4_HEADER_HPP
#include <algorithm>
#include <asio/ip/address_v4.hpp>
// Packet header for IPv4.
//
// The wire format of an IPv4 header is:
//
// 0 8 16 31
// +-------+-------+---------------+------------------------------+ ---
// | | | | | ^
// |version|header | type of | total length in bytes | |
// | (4) | length| service | | |
// +-------+-------+---------------+-+-+-+------------------------+ |
// | | | | | | |
// | identification |0|D|M| fragment offset | |
// | | |F|F| | |
// +---------------+---------------+-+-+-+------------------------+ |
// | | | | |
// | time to live | protocol | header checksum | 20 bytes
// | | | | |
// +---------------+---------------+------------------------------+ |
// | | |
// | source IPv4 address | |
// | | |
// +--------------------------------------------------------------+ |
// | | |
// | destination IPv4 address | |
// | | v
// +--------------------------------------------------------------+ ---
// | | ^
// | | |
// / options (if any) / 0 - 40
// / / bytes
// | | |
// | | v
// +--------------------------------------------------------------+ ---
class ipv4_header
{
public:
ipv4_header() { std::fill(rep_, rep_ + sizeof(rep_), 0); }
unsigned char version() const { return (rep_[0] >> 4) & 0xF; }
unsigned short header_length() const { return (rep_[0] & 0xF) * 4; }
unsigned char type_of_service() const { return rep_[1]; }
unsigned short total_length() const { return decode(2, 3); }
unsigned short identification() const { return decode(4, 5); }
bool dont_fragment() const { return (rep_[6] & 0x40) != 0; }
bool more_fragments() const { return (rep_[6] & 0x20) != 0; }
unsigned short fragment_offset() const { return decode(6, 7) & 0x1FFF; }
unsigned int time_to_live() const { return rep_[8]; }
unsigned char protocol() const { return rep_[9]; }
unsigned short header_checksum() const { return decode(10, 11); }
asio::ip::address_v4 source_address() const
{
asio::ip::address_v4::bytes_type bytes
= { { rep_[12], rep_[13], rep_[14], rep_[15] } };
return asio::ip::address_v4(bytes);
}
asio::ip::address_v4 destination_address() const
{
asio::ip::address_v4::bytes_type bytes
= { { rep_[16], rep_[17], rep_[18], rep_[19] } };
return asio::ip::address_v4(bytes);
}
friend std::istream& operator>>(std::istream& is, ipv4_header& header)
{
is.read(reinterpret_cast<char*>(header.rep_), 20);
if (header.version() != 4)
is.setstate(std::ios::failbit);
std::streamsize options_length = header.header_length() - 20;
if (options_length < 0 || options_length > 40)
is.setstate(std::ios::failbit);
else
is.read(reinterpret_cast<char*>(header.rep_) + 20, options_length);
return is;
}
private:
unsigned short decode(int a, int b) const
{ return (rep_[a] << 8) + rep_[b]; }
unsigned char rep_[60];
};
#endif // IPV4_HEADER_HPP
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/icmp/ping.cpp | //
// ping.cpp
// ~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio.hpp>
#include <istream>
#include <iostream>
#include <ostream>
#include "icmp_header.hpp"
#include "ipv4_header.hpp"
using asio::ip::icmp;
using asio::steady_timer;
namespace chrono = asio::chrono;
class pinger
{
public:
pinger(asio::io_context& io_context, const char* destination)
: resolver_(io_context), socket_(io_context, icmp::v4()),
timer_(io_context), sequence_number_(0), num_replies_(0)
{
destination_ = *resolver_.resolve(icmp::v4(), destination, "").begin();
start_send();
start_receive();
}
private:
void start_send()
{
std::string body("\"Hello!\" from Asio ping.");
// Create an ICMP header for an echo request.
icmp_header echo_request;
echo_request.type(icmp_header::echo_request);
echo_request.code(0);
echo_request.identifier(get_identifier());
echo_request.sequence_number(++sequence_number_);
compute_checksum(echo_request, body.begin(), body.end());
// Encode the request packet.
asio::streambuf request_buffer;
std::ostream os(&request_buffer);
os << echo_request << body;
// Send the request.
time_sent_ = steady_timer::clock_type::now();
socket_.send_to(request_buffer.data(), destination_);
// Wait up to five seconds for a reply.
num_replies_ = 0;
timer_.expires_at(time_sent_ + chrono::seconds(5));
timer_.async_wait(std::bind(&pinger::handle_timeout, this));
}
void handle_timeout()
{
if (num_replies_ == 0)
std::cout << "Request timed out" << std::endl;
// Requests must be sent no less than one second apart.
timer_.expires_at(time_sent_ + chrono::seconds(1));
timer_.async_wait(std::bind(&pinger::start_send, this));
}
void start_receive()
{
// Discard any data already in the buffer.
reply_buffer_.consume(reply_buffer_.size());
// Wait for a reply. We prepare the buffer to receive up to 64KB.
socket_.async_receive(reply_buffer_.prepare(65536),
std::bind(&pinger::handle_receive, this, std::placeholders::_2));
}
void handle_receive(std::size_t length)
{
// The actual number of bytes received is committed to the buffer so that we
// can extract it using a std::istream object.
reply_buffer_.commit(length);
// Decode the reply packet.
std::istream is(&reply_buffer_);
ipv4_header ipv4_hdr;
icmp_header icmp_hdr;
is >> ipv4_hdr >> icmp_hdr;
// We can receive all ICMP packets received by the host, so we need to
// filter out only the echo replies that match the our identifier and
// expected sequence number.
if (is && icmp_hdr.type() == icmp_header::echo_reply
&& icmp_hdr.identifier() == get_identifier()
&& icmp_hdr.sequence_number() == sequence_number_)
{
// If this is the first reply, interrupt the five second timeout.
if (num_replies_++ == 0)
timer_.cancel();
// Print out some information about the reply packet.
chrono::steady_clock::time_point now = chrono::steady_clock::now();
chrono::steady_clock::duration elapsed = now - time_sent_;
std::cout << length - ipv4_hdr.header_length()
<< " bytes from " << ipv4_hdr.source_address()
<< ": icmp_seq=" << icmp_hdr.sequence_number()
<< ", ttl=" << ipv4_hdr.time_to_live()
<< ", time="
<< chrono::duration_cast<chrono::milliseconds>(elapsed).count()
<< std::endl;
}
start_receive();
}
static unsigned short get_identifier()
{
#if defined(ASIO_WINDOWS)
return static_cast<unsigned short>(::GetCurrentProcessId());
#else
return static_cast<unsigned short>(::getpid());
#endif
}
icmp::resolver resolver_;
icmp::endpoint destination_;
icmp::socket socket_;
steady_timer timer_;
unsigned short sequence_number_;
chrono::steady_clock::time_point time_sent_;
asio::streambuf reply_buffer_;
std::size_t num_replies_;
};
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: ping <host>" << std::endl;
#if !defined(ASIO_WINDOWS)
std::cerr << "(You may need to run this program as root.)" << std::endl;
#endif
return 1;
}
asio::io_context io_context;
pinger p(io_context, argv[1]);
io_context.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << std::endl;
}
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/icmp/icmp_header.hpp | //
// icmp_header.hpp
// ~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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)
//
#ifndef ICMP_HEADER_HPP
#define ICMP_HEADER_HPP
#include <istream>
#include <ostream>
#include <algorithm>
// ICMP header for both IPv4 and IPv6.
//
// The wire format of an ICMP header is:
//
// 0 8 16 31
// +---------------+---------------+------------------------------+ ---
// | | | | ^
// | type | code | checksum | |
// | | | | |
// +---------------+---------------+------------------------------+ 8 bytes
// | | | |
// | identifier | sequence number | |
// | | | v
// +-------------------------------+------------------------------+ ---
class icmp_header
{
public:
enum { echo_reply = 0, destination_unreachable = 3, source_quench = 4,
redirect = 5, echo_request = 8, time_exceeded = 11, parameter_problem = 12,
timestamp_request = 13, timestamp_reply = 14, info_request = 15,
info_reply = 16, address_request = 17, address_reply = 18 };
icmp_header() { std::fill(rep_, rep_ + sizeof(rep_), 0); }
unsigned char type() const { return rep_[0]; }
unsigned char code() const { return rep_[1]; }
unsigned short checksum() const { return decode(2, 3); }
unsigned short identifier() const { return decode(4, 5); }
unsigned short sequence_number() const { return decode(6, 7); }
void type(unsigned char n) { rep_[0] = n; }
void code(unsigned char n) { rep_[1] = n; }
void checksum(unsigned short n) { encode(2, 3, n); }
void identifier(unsigned short n) { encode(4, 5, n); }
void sequence_number(unsigned short n) { encode(6, 7, n); }
friend std::istream& operator>>(std::istream& is, icmp_header& header)
{ return is.read(reinterpret_cast<char*>(header.rep_), 8); }
friend std::ostream& operator<<(std::ostream& os, const icmp_header& header)
{ return os.write(reinterpret_cast<const char*>(header.rep_), 8); }
private:
unsigned short decode(int a, int b) const
{ return (rep_[a] << 8) + rep_[b]; }
void encode(int a, int b, unsigned short n)
{
rep_[a] = static_cast<unsigned char>(n >> 8);
rep_[b] = static_cast<unsigned char>(n & 0xFF);
}
unsigned char rep_[8];
};
template <typename Iterator>
void compute_checksum(icmp_header& header,
Iterator body_begin, Iterator body_end)
{
unsigned int sum = (header.type() << 8) + header.code()
+ header.identifier() + header.sequence_number();
Iterator body_iter = body_begin;
while (body_iter != body_end)
{
sum += (static_cast<unsigned char>(*body_iter++) << 8);
if (body_iter != body_end)
sum += static_cast<unsigned char>(*body_iter++);
}
sum = (sum >> 16) + (sum & 0xFFFF);
sum += (sum >> 16);
header.checksum(static_cast<unsigned short>(~sum));
}
#endif // ICMP_HEADER_HPP
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/services/logger.hpp | //
// logger.hpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2024 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)
//
#ifndef SERVICES_LOGGER_HPP
#define SERVICES_LOGGER_HPP
#include "basic_logger.hpp"
#include "logger_service.hpp"
namespace services {
/// Typedef for typical logger usage.
typedef basic_logger<logger_service> logger;
} // namespace services
#endif // SERVICES_LOGGER_HPP
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/services/basic_logger.hpp | //
// basic_logger.hpp
// ~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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)
//
#ifndef SERVICES_BASIC_LOGGER_HPP
#define SERVICES_BASIC_LOGGER_HPP
#include <asio.hpp>
#include <string>
namespace services {
/// Class to provide simple logging functionality. Use the services::logger
/// typedef.
template <typename Service>
class basic_logger
{
public:
/// The type of the service that will be used to provide timer operations.
typedef Service service_type;
/// The native implementation type of the timer.
typedef typename service_type::impl_type impl_type;
/// Constructor.
/**
* This constructor creates a logger.
*
* @param context The execution context used to locate the logger service.
*
* @param identifier An identifier for this logger.
*/
explicit basic_logger(asio::execution_context& context,
const std::string& identifier)
: service_(asio::use_service<Service>(context)),
impl_(service_.null())
{
service_.create(impl_, identifier);
}
basic_logger(const basic_logger&) = delete;
basic_logger& operator=(basic_logger&) = delete;
/// Destructor.
~basic_logger()
{
service_.destroy(impl_);
}
/// Set the output file for all logger instances.
void use_file(const std::string& file)
{
service_.use_file(impl_, file);
}
/// Log a message.
void log(const std::string& message)
{
service_.log(impl_, message);
}
private:
/// The backend service implementation.
service_type& service_;
/// The underlying native implementation.
impl_type impl_;
};
} // namespace services
#endif // SERVICES_BASIC_LOGGER_HPP
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/services/logger_service.hpp | //
// logger_service.hpp
// ~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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)
//
#ifndef SERVICES_LOGGER_SERVICE_HPP
#define SERVICES_LOGGER_SERVICE_HPP
#include <asio.hpp>
#include <functional>
#include <fstream>
#include <sstream>
#include <string>
#include <thread>
namespace services {
/// Service implementation for the logger.
class logger_service
: public asio::execution_context::service
{
public:
/// The type used to identify this service in the execution context.
typedef logger_service key_type;
/// The backend implementation of a logger.
struct logger_impl
{
explicit logger_impl(const std::string& ident) : identifier(ident) {}
std::string identifier;
};
/// The type for an implementation of the logger.
typedef logger_impl* impl_type;
/// Constructor creates a thread to run a private io_context.
logger_service(asio::execution_context& context)
: asio::execution_context::service(context),
work_io_context_(),
work_(asio::make_work_guard(work_io_context_)),
work_thread_([this]{ work_io_context_.run(); })
{
}
logger_service(const logger_service&) = delete;
logger_service& operator=(const logger_service&) = delete;;
/// Destructor shuts down the private io_context.
~logger_service()
{
/// Indicate that we have finished with the private io_context. Its
/// io_context::run() function will exit once all other work has completed.
work_.reset();
if (work_thread_.joinable())
work_thread_.join();
}
/// Destroy all user-defined handler objects owned by the service.
void shutdown()
{
}
/// Return a null logger implementation.
impl_type null() const
{
return 0;
}
/// Create a new logger implementation.
void create(impl_type& impl, const std::string& identifier)
{
impl = new logger_impl(identifier);
}
/// Destroy a logger implementation.
void destroy(impl_type& impl)
{
delete impl;
impl = null();
}
/// Set the output file for the logger. The current implementation sets the
/// output file for all logger instances, and so the impl parameter is not
/// actually needed. It is retained here to illustrate how service functions
/// are typically defined.
void use_file(impl_type& /*impl*/, const std::string& file)
{
// Pass the work of opening the file to the background thread.
asio::post(work_io_context_,
std::bind(&logger_service::use_file_impl, this, file));
}
/// Log a message.
void log(impl_type& impl, const std::string& message)
{
// Format the text to be logged.
std::ostringstream os;
os << impl->identifier << ": " << message;
// Pass the work of writing to the file to the background thread.
asio::post(work_io_context_,
std::bind(&logger_service::log_impl, this, os.str()));
}
private:
/// Helper function used to open the output file from within the private
/// io_context's thread.
void use_file_impl(const std::string& file)
{
ofstream_.close();
ofstream_.clear();
ofstream_.open(file.c_str());
}
/// Helper function used to log a message from within the private io_context's
/// thread.
void log_impl(const std::string& text)
{
ofstream_ << text << std::endl;
}
/// Private io_context used for performing logging operations.
asio::io_context work_io_context_;
/// Work for the private io_context to perform. If we do not give the
/// io_context some work to do then the io_context::run() function will exit
/// immediately.
asio::executor_work_guard<
asio::io_context::executor_type> work_;
/// Thread used for running the work io_context's run loop.
std::thread work_thread_;
/// The file to which log messages will be written.
std::ofstream ofstream_;
};
} // namespace services
#endif // SERVICES_LOGGER_SERVICE_HPP
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/services/daytime_client.cpp | //
// daytime_client.cpp
// ~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio.hpp>
#include <functional>
#include <iostream>
#include "logger.hpp"
using asio::ip::tcp;
char read_buffer[1024];
void read_handler(const asio::error_code& e,
std::size_t bytes_transferred, tcp::socket* s)
{
if (!e)
{
std::cout.write(read_buffer, bytes_transferred);
s->async_read_some(asio::buffer(read_buffer),
std::bind(read_handler, asio::placeholders::error,
asio::placeholders::bytes_transferred, s));
}
else
{
asio::execution_context& context = asio::query(
s->get_executor(), asio::execution::context);
services::logger logger(context, "read_handler");
std::string msg = "Read error: ";
msg += e.message();
logger.log(msg);
}
}
void connect_handler(const asio::error_code& e, tcp::socket* s)
{
asio::execution_context& context = asio::query(
s->get_executor(), asio::execution::context);
services::logger logger(context, "connect_handler");
if (!e)
{
logger.log("Connection established");
s->async_read_some(asio::buffer(read_buffer),
std::bind(read_handler, asio::placeholders::error,
asio::placeholders::bytes_transferred, s));
}
else
{
std::string msg = "Unable to establish connection: ";
msg += e.message();
logger.log(msg);
}
}
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: daytime_client <host>" << std::endl;
return 1;
}
asio::io_context io_context;
// Set the name of the file that all logger instances will use.
services::logger logger(io_context, "");
logger.use_file("log.txt");
// Resolve the address corresponding to the given host.
tcp::resolver resolver(io_context);
tcp::resolver::results_type endpoints =
resolver.resolve(argv[1], "daytime");
// Start an asynchronous connect.
tcp::socket socket(io_context);
asio::async_connect(socket, endpoints,
std::bind(connect_handler,
asio::placeholders::error, &socket));
// Run the io_context until all operations have finished.
io_context.run();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/services/logger_service.cpp | //
// logger_service.cpp
// ~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 "logger_service.hpp"
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/type_erasure/sleep.hpp | //
// sleep.hpp
// ~~~~~~~~~
//
// Copyright (c) 2003-2024 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)
//
#ifndef SLEEP_HPP
#define SLEEP_HPP
#include <asio/any_completion_handler.hpp>
#include <asio/any_io_executor.hpp>
#include <asio/async_result.hpp>
#include <asio/error.hpp>
#include <chrono>
void async_sleep_impl(
asio::any_completion_handler<void(std::error_code)> handler,
asio::any_io_executor ex, std::chrono::nanoseconds duration);
template <typename CompletionToken>
inline auto async_sleep(asio::any_io_executor ex,
std::chrono::nanoseconds duration, CompletionToken&& token)
-> decltype(
asio::async_initiate<CompletionToken, void(std::error_code)>(
async_sleep_impl, token, std::move(ex), duration))
{
return asio::async_initiate<CompletionToken, void(std::error_code)>(
async_sleep_impl, token, std::move(ex), duration);
}
#endif // SLEEP_HPP
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/type_erasure/line_reader.hpp | //
// line_reader.hpp
// ~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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)
//
#ifndef LINE_READER_HPP
#define LINE_READER_HPP
#include <asio/any_completion_handler.hpp>
#include <asio/async_result.hpp>
#include <asio/error.hpp>
#include <string>
class line_reader
{
private:
virtual void async_read_line_impl(std::string prompt,
asio::any_completion_handler<void(std::error_code, std::string)> handler) = 0;
struct initiate_read_line
{
template <typename Handler>
void operator()(Handler handler, line_reader* self, std::string prompt)
{
self->async_read_line_impl(std::move(prompt), std::move(handler));
}
};
public:
virtual ~line_reader() {}
template <typename CompletionToken>
auto async_read_line(std::string prompt, CompletionToken&& token)
-> decltype(
asio::async_initiate<CompletionToken, void(std::error_code, std::string)>(
initiate_read_line(), token, this, prompt))
{
return asio::async_initiate<CompletionToken, void(std::error_code, std::string)>(
initiate_read_line(), token, this, prompt);
}
};
#endif // LINE_READER_HPP
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/type_erasure/stdin_line_reader.hpp | //
// stdin_line_reader.hpp
// ~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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)
//
#ifndef STDIN_LINE_READER_HPP
#define STDIN_LINE_READER_HPP
#include "line_reader.hpp"
#include <asio/posix/stream_descriptor.hpp>
class stdin_line_reader : public line_reader
{
public:
explicit stdin_line_reader(asio::any_io_executor ex);
private:
void async_read_line_impl(std::string prompt,
asio::any_completion_handler<void(std::error_code, std::string)> handler) override;
asio::posix::stream_descriptor stdin_;
std::string buffer_;
};
#endif
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/type_erasure/stdin_line_reader.cpp | //
// stdin_line_reader.cpp
// ~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 "stdin_line_reader.hpp"
#include <asio/deferred.hpp>
#include <asio/read_until.hpp>
#include <iostream>
stdin_line_reader::stdin_line_reader(asio::any_io_executor ex)
: stdin_(ex, ::dup(STDIN_FILENO))
{
}
void stdin_line_reader::async_read_line_impl(std::string prompt,
asio::any_completion_handler<void(std::error_code, std::string)> handler)
{
std::cout << prompt;
std::cout.flush();
asio::async_read_until(stdin_, asio::dynamic_buffer(buffer_), '\n',
asio::deferred(
[this](std::error_code ec, std::size_t n)
{
if (!ec)
{
std::string result = buffer_.substr(0, n);
buffer_.erase(0, n);
return asio::deferred.values(ec, std::move(result));
}
else
{
return asio::deferred.values(ec, std::string{});
}
}
)
)(std::move(handler));
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/type_erasure/sleep.cpp | //
// sleep.cpp
// ~~~~~~~~~
//
// Copyright (c) 2003-2024 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 "sleep.hpp"
#include <asio/consign.hpp>
#include <asio/steady_timer.hpp>
#include <memory>
void async_sleep_impl(
asio::any_completion_handler<void(std::error_code)> handler,
asio::any_io_executor ex, std::chrono::nanoseconds duration)
{
auto timer = std::make_shared<asio::steady_timer>(ex, duration);
timer->async_wait(asio::consign(std::move(handler), timer));
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/type_erasure/main.cpp | //
// main.cpp
// ~~~~~~~~
//
// Copyright (c) 2003-2024 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 "line_reader.hpp"
#include "sleep.hpp"
#include "stdin_line_reader.hpp"
#include <asio/coroutine.hpp>
#include <asio/detached.hpp>
#include <asio/io_context.hpp>
#include <asio/use_awaitable.hpp>
#include <iostream>
#include <asio/yield.hpp>
class read_loop : asio::coroutine
{
public:
read_loop(asio::any_io_executor e, line_reader& r)
: executor(std::move(e)),
reader(r)
{
}
void operator()(std::error_code ec = {}, std::string line = {})
{
reenter (this)
{
for (i = 0; i < 10; ++i)
{
yield reader.async_read_line("Enter something: ", *this);
if (ec) break;
std::cout << line;
yield async_sleep(executor, std::chrono::seconds(1), *this);
if (ec) break;
}
}
}
private:
asio::any_io_executor executor;
line_reader& reader;
int i;
};
#include <asio/unyield.hpp>
int main()
{
asio::io_context ctx{1};
stdin_line_reader reader{ctx.get_executor()};
read_loop(ctx.get_executor(), reader)();
ctx.run();
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/timers/time_t_timer.cpp | //
// time_t_timer.cpp
// ~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio.hpp>
#include <ctime>
#include <chrono>
#include <iostream>
// A custom implementation of the Clock concept from the standard C++ library.
struct time_t_clock
{
// The duration type.
typedef std::chrono::steady_clock::duration duration;
// The duration's underlying arithmetic representation.
typedef duration::rep rep;
// The ratio representing the duration's tick period.
typedef duration::period period;
// An absolute time point represented using the clock.
typedef std::chrono::time_point<time_t_clock> time_point;
// The clock is not monotonically increasing.
static constexpr bool is_steady = false;
// Get the current time.
static time_point now() noexcept
{
return time_point() + std::chrono::seconds(std::time(0));
}
};
// The asio::basic_waitable_timer template accepts an optional WaitTraits
// template parameter. The underlying time_t clock has one-second granularity,
// so these traits may be customised to reduce the latency between the clock
// ticking over and a wait operation's completion. When the timeout is near
// (less than one second away) we poll the clock more frequently to detect the
// time change closer to when it occurs. The user can select the appropriate
// trade off between accuracy and the increased CPU cost of polling. In extreme
// cases, a zero duration may be returned to make the timers as accurate as
// possible, albeit with 100% CPU usage.
struct time_t_wait_traits
{
// Determine how long until the clock should be next polled to determine
// whether the duration has elapsed.
static time_t_clock::duration to_wait_duration(
const time_t_clock::duration& d)
{
if (d > std::chrono::seconds(1))
return d - std::chrono::seconds(1);
else if (d > std::chrono::seconds(0))
return std::chrono::milliseconds(10);
else
return std::chrono::seconds(0);
}
// Determine how long until the clock should be next polled to determine
// whether the absoluate time has been reached.
static time_t_clock::duration to_wait_duration(
const time_t_clock::time_point& t)
{
return to_wait_duration(t - time_t_clock::now());
}
};
typedef asio::basic_waitable_timer<
time_t_clock, time_t_wait_traits> time_t_timer;
int main()
{
try
{
asio::io_context io_context;
time_t_timer timer(io_context);
timer.expires_after(std::chrono::seconds(5));
std::cout << "Starting synchronous wait\n";
timer.wait();
std::cout << "Finished synchronous wait\n";
timer.expires_after(std::chrono::seconds(5));
std::cout << "Starting asynchronous wait\n";
timer.async_wait(
[](const std::error_code& /*error*/)
{
std::cout << "timeout\n";
});
io_context.run();
std::cout << "Finished asynchronous wait\n";
}
catch (std::exception& e)
{
std::cout << "Exception: " << e.what() << "\n";
}
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/fork/process_per_connection.cpp | //
// process_per_connection.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio/io_context.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/signal_set.hpp>
#include <asio/write.hpp>
#include <cstdlib>
#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
using asio::ip::tcp;
class server
{
public:
server(asio::io_context& io_context, unsigned short port)
: io_context_(io_context),
signal_(io_context, SIGCHLD),
acceptor_(io_context, {tcp::v4(), port}),
socket_(io_context)
{
wait_for_signal();
accept();
}
private:
void wait_for_signal()
{
signal_.async_wait(
[this](std::error_code /*ec*/, int /*signo*/)
{
// Only the parent process should check for this signal. We can
// determine whether we are in the parent by checking if the acceptor
// is still open.
if (acceptor_.is_open())
{
// Reap completed child processes so that we don't end up with
// zombies.
int status = 0;
while (waitpid(-1, &status, WNOHANG) > 0) {}
wait_for_signal();
}
});
}
void accept()
{
acceptor_.async_accept(
[this](std::error_code ec, tcp::socket new_socket)
{
if (!ec)
{
// Take ownership of the newly accepted socket.
socket_ = std::move(new_socket);
// Inform the io_context that we are about to fork. The io_context
// cleans up any internal resources, such as threads, that may
// interfere with forking.
io_context_.notify_fork(asio::io_context::fork_prepare);
if (fork() == 0)
{
// Inform the io_context that the fork is finished and that this
// is the child process. The io_context uses this opportunity to
// create any internal file descriptors that must be private to
// the new process.
io_context_.notify_fork(asio::io_context::fork_child);
// The child won't be accepting new connections, so we can close
// the acceptor. It remains open in the parent.
acceptor_.close();
// The child process is not interested in processing the SIGCHLD
// signal.
signal_.cancel();
read();
}
else
{
// Inform the io_context that the fork is finished (or failed)
// and that this is the parent process. The io_context uses this
// opportunity to recreate any internal resources that were
// cleaned up during preparation for the fork.
io_context_.notify_fork(asio::io_context::fork_parent);
// The parent process can now close the newly accepted socket. It
// remains open in the child.
socket_.close();
accept();
}
}
else
{
std::cerr << "Accept error: " << ec.message() << std::endl;
accept();
}
});
}
void read()
{
socket_.async_read_some(asio::buffer(data_),
[this](std::error_code ec, std::size_t length)
{
if (!ec)
write(length);
});
}
void write(std::size_t length)
{
asio::async_write(socket_, asio::buffer(data_, length),
[this](std::error_code ec, std::size_t /*length*/)
{
if (!ec)
read();
});
}
asio::io_context& io_context_;
asio::signal_set signal_;
tcp::acceptor acceptor_;
tcp::socket socket_;
std::array<char, 1024> data_;
};
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: process_per_connection <port>\n";
return 1;
}
asio::io_context io_context;
using namespace std; // For atoi.
server s(io_context, atoi(argv[1]));
io_context.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << std::endl;
}
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/fork/daemon.cpp | //
// daemon.cpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio/io_context.hpp>
#include <asio/ip/udp.hpp>
#include <asio/signal_set.hpp>
#include <array>
#include <ctime>
#include <iostream>
#include <syslog.h>
#include <unistd.h>
using asio::ip::udp;
class udp_daytime_server
{
public:
udp_daytime_server(asio::io_context& io_context)
: socket_(io_context, {udp::v4(), 13})
{
receive();
}
private:
void receive()
{
socket_.async_receive_from(
asio::buffer(recv_buffer_), remote_endpoint_,
[this](std::error_code ec, std::size_t /*n*/)
{
if (!ec)
{
using namespace std; // For time_t, time and ctime;
time_t now = time(0);
std::string message = ctime(&now);
std::error_code ignored_ec;
socket_.send_to(asio::buffer(message),
remote_endpoint_, 0, ignored_ec);
}
receive();
});
}
udp::socket socket_;
udp::endpoint remote_endpoint_;
std::array<char, 1> recv_buffer_;
};
int main()
{
try
{
asio::io_context io_context;
// Initialise the server before becoming a daemon. If the process is
// started from a shell, this means any errors will be reported back to the
// user.
udp_daytime_server server(io_context);
// Register signal handlers so that the daemon may be shut down. You may
// also want to register for other signals, such as SIGHUP to trigger a
// re-read of a configuration file.
asio::signal_set signals(io_context, SIGINT, SIGTERM);
signals.async_wait(
[&](std::error_code /*ec*/, int /*signo*/)
{
io_context.stop();
});
// Inform the io_context that we are about to become a daemon. The
// io_context cleans up any internal resources, such as threads, that may
// interfere with forking.
io_context.notify_fork(asio::io_context::fork_prepare);
// Fork the process and have the parent exit. If the process was started
// from a shell, this returns control to the user. Forking a new process is
// also a prerequisite for the subsequent call to setsid().
if (pid_t pid = fork())
{
if (pid > 0)
{
// We're in the parent process and need to exit.
//
// When the exit() function is used, the program terminates without
// invoking local variables' destructors. Only global variables are
// destroyed. As the io_context object is a local variable, this means
// we do not have to call:
//
// io_context.notify_fork(asio::io_context::fork_parent);
//
// However, this line should be added before each call to exit() if
// using a global io_context object. An additional call:
//
// io_context.notify_fork(asio::io_context::fork_prepare);
//
// should also precede the second fork().
exit(0);
}
else
{
syslog(LOG_ERR | LOG_USER, "First fork failed: %m");
return 1;
}
}
// Make the process a new session leader. This detaches it from the
// terminal.
setsid();
// A process inherits its working directory from its parent. This could be
// on a mounted filesystem, which means that the running daemon would
// prevent this filesystem from being unmounted. Changing to the root
// directory avoids this problem.
chdir("/");
// The file mode creation mask is also inherited from the parent process.
// We don't want to restrict the permissions on files created by the
// daemon, so the mask is cleared.
umask(0);
// A second fork ensures the process cannot acquire a controlling terminal.
if (pid_t pid = fork())
{
if (pid > 0)
{
exit(0);
}
else
{
syslog(LOG_ERR | LOG_USER, "Second fork failed: %m");
return 1;
}
}
// Close the standard streams. This decouples the daemon from the terminal
// that started it.
close(0);
close(1);
close(2);
// We don't want the daemon to have any standard input.
if (open("/dev/null", O_RDONLY) < 0)
{
syslog(LOG_ERR | LOG_USER, "Unable to open /dev/null: %m");
return 1;
}
// Send standard output to a log file.
const char* output = "/tmp/asio.daemon.out";
const int flags = O_WRONLY | O_CREAT | O_APPEND;
const mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
if (open(output, flags, mode) < 0)
{
syslog(LOG_ERR | LOG_USER, "Unable to open output file %s: %m", output);
return 1;
}
// Also send standard error to the same log file.
if (dup(1) < 0)
{
syslog(LOG_ERR | LOG_USER, "Unable to dup output descriptor: %m");
return 1;
}
// Inform the io_context that we have finished becoming a daemon. The
// io_context uses this opportunity to create any internal file descriptors
// that need to be private to the new process.
io_context.notify_fork(asio::io_context::fork_child);
// The io_context can now be used normally.
syslog(LOG_INFO | LOG_USER, "Daemon started");
io_context.run();
syslog(LOG_INFO | LOG_USER, "Daemon stopped");
}
catch (std::exception& e)
{
syslog(LOG_ERR | LOG_USER, "Exception: %s", e.what());
std::cerr << "Exception: " << e.what() << std::endl;
}
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/nonblocking/third_party_lib.cpp | //
// third_party_lib.cpp
// ~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio.hpp>
#include <array>
#include <iostream>
#include <memory>
using asio::ip::tcp;
namespace third_party_lib {
// Simulation of a third party library that wants to perform read and write
// operations directly on a socket. It needs to be polled to determine whether
// it requires a read or write operation, and notified when the socket is ready
// for reading or writing.
class session
{
public:
session(tcp::socket& socket)
: socket_(socket)
{
}
// Returns true if the third party library wants to be notified when the
// socket is ready for reading.
bool want_read() const
{
return state_ == reading;
}
// Notify that third party library that it should perform its read operation.
void do_read(std::error_code& ec)
{
if (std::size_t len = socket_.read_some(asio::buffer(data_), ec))
{
write_buffer_ = asio::buffer(data_, len);
state_ = writing;
}
}
// Returns true if the third party library wants to be notified when the
// socket is ready for writing.
bool want_write() const
{
return state_ == writing;
}
// Notify that third party library that it should perform its write operation.
void do_write(std::error_code& ec)
{
if (std::size_t len = socket_.write_some(
asio::buffer(write_buffer_), ec))
{
write_buffer_ = write_buffer_ + len;
state_ = asio::buffer_size(write_buffer_) > 0 ? writing : reading;
}
}
private:
tcp::socket& socket_;
enum { reading, writing } state_ = reading;
std::array<char, 128> data_;
asio::const_buffer write_buffer_;
};
} // namespace third_party_lib
// The glue between asio's sockets and the third party library.
class connection
: public std::enable_shared_from_this<connection>
{
public:
connection(tcp::socket socket)
: socket_(std::move(socket))
{
}
void start()
{
// Put the socket into non-blocking mode.
socket_.non_blocking(true);
do_operations();
}
private:
void do_operations()
{
auto self(shared_from_this());
// Start a read operation if the third party library wants one.
if (session_impl_.want_read() && !read_in_progress_)
{
read_in_progress_ = true;
socket_.async_wait(tcp::socket::wait_read,
[this, self](std::error_code ec)
{
read_in_progress_ = false;
// Notify third party library that it can perform a read.
if (!ec)
session_impl_.do_read(ec);
// The third party library successfully performed a read on the
// socket. Start new read or write operations based on what it now
// wants.
if (!ec || ec == asio::error::would_block)
do_operations();
// Otherwise, an error occurred. Closing the socket cancels any
// outstanding asynchronous read or write operations. The
// connection object will be destroyed automatically once those
// outstanding operations complete.
else
socket_.close();
});
}
// Start a write operation if the third party library wants one.
if (session_impl_.want_write() && !write_in_progress_)
{
write_in_progress_ = true;
socket_.async_wait(tcp::socket::wait_write,
[this, self](std::error_code ec)
{
write_in_progress_ = false;
// Notify third party library that it can perform a write.
if (!ec)
session_impl_.do_write(ec);
// The third party library successfully performed a write on the
// socket. Start new read or write operations based on what it now
// wants.
if (!ec || ec == asio::error::would_block)
do_operations();
// Otherwise, an error occurred. Closing the socket cancels any
// outstanding asynchronous read or write operations. The
// connection object will be destroyed automatically once those
// outstanding operations complete.
else
socket_.close();
});
}
}
private:
tcp::socket socket_;
third_party_lib::session session_impl_{socket_};
bool read_in_progress_ = false;
bool write_in_progress_ = false;
};
class server
{
public:
server(asio::io_context& io_context, unsigned short port)
: acceptor_(io_context, {tcp::v4(), port})
{
do_accept();
}
private:
void do_accept()
{
acceptor_.async_accept(
[this](std::error_code ec, tcp::socket socket)
{
if (!ec)
{
std::make_shared<connection>(std::move(socket))->start();
}
do_accept();
});
}
tcp::acceptor acceptor_;
};
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: third_party_lib <port>\n";
return 1;
}
asio::io_context io_context;
server s(io_context, std::atoi(argv[1]));
io_context.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/futures/daytime_client.cpp | //
// daytime_client.cpp
// ~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <array>
#include <future>
#include <iostream>
#include <thread>
#include <asio/io_context.hpp>
#include <asio/ip/udp.hpp>
#include <asio/use_future.hpp>
using asio::ip::udp;
void get_daytime(asio::io_context& io_context, const char* hostname)
{
try
{
udp::resolver resolver(io_context);
std::future<udp::resolver::results_type> endpoints =
resolver.async_resolve(
udp::v4(), hostname, "daytime",
asio::use_future);
// The async_resolve operation above returns the endpoints as a future
// value that is not retrieved ...
udp::socket socket(io_context, udp::v4());
std::array<char, 1> send_buf = {{ 0 }};
std::future<std::size_t> send_length =
socket.async_send_to(asio::buffer(send_buf),
*endpoints.get().begin(), // ... until here. This call may block.
asio::use_future);
// Do other things here while the send completes.
send_length.get(); // Blocks until the send is complete. Throws any errors.
std::array<char, 128> recv_buf;
udp::endpoint sender_endpoint;
std::future<std::size_t> recv_length =
socket.async_receive_from(
asio::buffer(recv_buf),
sender_endpoint,
asio::use_future);
// Do other things here while the receive completes.
std::cout.write(
recv_buf.data(),
recv_length.get()); // Blocks until receive is complete.
}
catch (std::system_error& e)
{
std::cerr << e.what() << std::endl;
}
}
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: daytime_client <host>" << std::endl;
return 1;
}
// We run the io_context off in its own thread so that it operates
// completely asynchronously with respect to the rest of the program.
asio::io_context io_context;
auto work = asio::make_work_guard(io_context);
std::thread thread([&io_context](){ io_context.run(); });
get_daytime(io_context, argv[1]);
io_context.stop();
thread.join();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/invocation/prioritised_handlers.cpp | //
// prioritised_handlers.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 "asio.hpp"
#include <iostream>
#include <memory>
#include <queue>
using asio::ip::tcp;
class handler_priority_queue : public asio::execution_context
{
public:
template <typename Function>
void add(int priority, Function function)
{
std::unique_ptr<queued_handler_base> handler(
new queued_handler<Function>(
priority, std::move(function)));
handlers_.push(std::move(handler));
}
void execute_all()
{
while (!handlers_.empty())
{
handlers_.top()->execute();
handlers_.pop();
}
}
class executor
{
public:
executor(handler_priority_queue& q, int p)
: context_(q), priority_(p)
{
}
handler_priority_queue& context() const noexcept
{
return context_;
}
template <typename Function, typename Allocator>
void dispatch(Function f, const Allocator&) const
{
context_.add(priority_, std::move(f));
}
template <typename Function, typename Allocator>
void post(Function f, const Allocator&) const
{
context_.add(priority_, std::move(f));
}
template <typename Function, typename Allocator>
void defer(Function f, const Allocator&) const
{
context_.add(priority_, std::move(f));
}
void on_work_started() const noexcept {}
void on_work_finished() const noexcept {}
bool operator==(const executor& other) const noexcept
{
return &context_ == &other.context_ && priority_ == other.priority_;
}
bool operator!=(const executor& other) const noexcept
{
return !operator==(other);
}
private:
handler_priority_queue& context_;
int priority_;
};
template <typename Handler>
asio::executor_binder<Handler, executor>
wrap(int priority, Handler handler)
{
return asio::bind_executor(
executor(*this, priority), std::move(handler));
}
private:
class queued_handler_base
{
public:
queued_handler_base(int p)
: priority_(p)
{
}
virtual ~queued_handler_base()
{
}
virtual void execute() = 0;
friend bool operator<(const std::unique_ptr<queued_handler_base>& a,
const std::unique_ptr<queued_handler_base>& b) noexcept
{
return a->priority_ < b->priority_;
}
private:
int priority_;
};
template <typename Function>
class queued_handler : public queued_handler_base
{
public:
queued_handler(int p, Function f)
: queued_handler_base(p), function_(std::move(f))
{
}
void execute() override
{
function_();
}
private:
Function function_;
};
std::priority_queue<std::unique_ptr<queued_handler_base>> handlers_;
};
//----------------------------------------------------------------------
void high_priority_handler(const std::error_code& /*ec*/,
tcp::socket /*socket*/)
{
std::cout << "High priority handler\n";
}
void middle_priority_handler(const std::error_code& /*ec*/)
{
std::cout << "Middle priority handler\n";
}
struct low_priority_handler
{
// Make the handler a move-only type.
low_priority_handler() = default;
low_priority_handler(const low_priority_handler&) = delete;
low_priority_handler(low_priority_handler&&) = default;
void operator()()
{
std::cout << "Low priority handler\n";
}
};
int main()
{
asio::io_context io_context;
handler_priority_queue pri_queue;
// Post a completion handler to be run immediately.
asio::post(io_context, pri_queue.wrap(0, low_priority_handler()));
// Start an asynchronous accept that will complete immediately.
tcp::endpoint endpoint(asio::ip::address_v4::loopback(), 0);
tcp::acceptor acceptor(io_context, endpoint);
tcp::socket server_socket(io_context);
acceptor.async_accept(pri_queue.wrap(100, high_priority_handler));
tcp::socket client_socket(io_context);
client_socket.connect(acceptor.local_endpoint());
// Set a deadline timer to expire immediately.
asio::steady_timer timer(io_context);
timer.expires_at(asio::steady_timer::clock_type::time_point::min());
timer.async_wait(pri_queue.wrap(42, middle_priority_handler));
while (io_context.run_one())
{
// The custom invocation hook adds the handlers to the priority queue
// rather than executing them from within the poll_one() call.
while (io_context.poll_one())
;
pri_queue.execute_all();
}
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/executors/bank_account_2.cpp | #include <asio/execution.hpp>
#include <asio/static_thread_pool.hpp>
#include <iostream>
using asio::static_thread_pool;
namespace execution = asio::execution;
// Traditional active object pattern.
// Member functions block until operation is finished.
class bank_account
{
int balance_ = 0;
mutable static_thread_pool pool_{1};
public:
void deposit(int amount)
{
asio::require(pool_.executor(), execution::blocking.always).execute(
[this, amount]
{
balance_ += amount;
});
}
void withdraw(int amount)
{
asio::require(pool_.executor(), execution::blocking.always).execute(
[this, amount]
{
if (balance_ >= amount)
balance_ -= amount;
});
}
int balance() const
{
int result = 0;
asio::require(pool_.executor(), execution::blocking.always).execute(
[this, &result]
{
result = balance_;
});
return result;
}
};
int main()
{
bank_account acct;
acct.deposit(20);
acct.withdraw(10);
std::cout << "balance = " << acct.balance() << "\n";
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/executors/pipeline.cpp | #include <asio/associated_executor.hpp>
#include <asio/bind_executor.hpp>
#include <asio/execution_context.hpp>
#include <asio/post.hpp>
#include <asio/system_executor.hpp>
#include <asio/use_future.hpp>
#include <condition_variable>
#include <future>
#include <memory>
#include <mutex>
#include <queue>
#include <thread>
#include <vector>
#include <cctype>
using asio::execution_context;
using asio::executor_binder;
using asio::get_associated_executor;
using asio::post;
using asio::system_executor;
using asio::use_future;
using asio::use_service;
namespace execution = asio::execution;
// An executor that launches a new thread for each function submitted to it.
// This class satisfies the executor requirements.
class thread_executor
{
private:
// Service to track all threads started through a thread_executor.
class thread_bag : public execution_context::service
{
public:
typedef thread_bag key_type;
explicit thread_bag(execution_context& ctx)
: execution_context::service(ctx)
{
}
void add_thread(std::thread&& t)
{
std::unique_lock<std::mutex> lock(mutex_);
threads_.push_back(std::move(t));
}
private:
virtual void shutdown()
{
for (auto& t : threads_)
t.join();
}
std::mutex mutex_;
std::vector<std::thread> threads_;
};
public:
execution_context& query(execution::context_t) const
{
return asio::query(system_executor(), execution::context);
}
execution::blocking_t query(execution::blocking_t) const
{
return execution::blocking.never;
}
thread_executor require(execution::blocking_t::never_t) const
{
return *this;
}
template <class Func>
void execute(Func f) const
{
thread_bag& bag = use_service<thread_bag>(query(execution::context));
bag.add_thread(std::thread(std::move(f)));
}
friend bool operator==(const thread_executor&,
const thread_executor&) noexcept
{
return true;
}
friend bool operator!=(const thread_executor&,
const thread_executor&) noexcept
{
return false;
}
};
// Base class for all thread-safe queue implementations.
class queue_impl_base
{
template <class> friend class queue_front;
template <class> friend class queue_back;
std::mutex mutex_;
std::condition_variable condition_;
bool stop_ = false;
};
// Underlying implementation of a thread-safe queue, shared between the
// queue_front and queue_back classes.
template <class T>
class queue_impl : public queue_impl_base
{
template <class> friend class queue_front;
template <class> friend class queue_back;
std::queue<T> queue_;
};
// The front end of a queue between consecutive pipeline stages.
template <class T>
class queue_front
{
public:
typedef T value_type;
explicit queue_front(std::shared_ptr<queue_impl<T>> impl)
: impl_(impl)
{
}
void push(T t)
{
std::unique_lock<std::mutex> lock(impl_->mutex_);
impl_->queue_.push(std::move(t));
impl_->condition_.notify_one();
}
void stop()
{
std::unique_lock<std::mutex> lock(impl_->mutex_);
impl_->stop_ = true;
impl_->condition_.notify_one();
}
private:
std::shared_ptr<queue_impl<T>> impl_;
};
// The back end of a queue between consecutive pipeline stages.
template <class T>
class queue_back
{
public:
typedef T value_type;
explicit queue_back(std::shared_ptr<queue_impl<T>> impl)
: impl_(impl)
{
}
bool pop(T& t)
{
std::unique_lock<std::mutex> lock(impl_->mutex_);
while (impl_->queue_.empty() && !impl_->stop_)
impl_->condition_.wait(lock);
if (!impl_->queue_.empty())
{
t = impl_->queue_.front();
impl_->queue_.pop();
return true;
}
return false;
}
private:
std::shared_ptr<queue_impl<T>> impl_;
};
// Launch the last stage in a pipeline.
template <class T, class F>
std::future<void> pipeline(queue_back<T> in, F f)
{
// Get the function's associated executor, defaulting to thread_executor.
auto ex = get_associated_executor(f, thread_executor());
// Run the function, and as we're the last stage return a future so that the
// caller can wait for the pipeline to finish.
return post(ex, use_future([in, f]() mutable { f(in); }));
}
// Launch an intermediate stage in a pipeline.
template <class T, class F, class... Tail>
std::future<void> pipeline(queue_back<T> in, F f, Tail... t)
{
// Determine the output queue type.
typedef typename executor_binder<F, thread_executor>::second_argument_type::value_type output_value_type;
// Create the output queue and its implementation.
auto out_impl = std::make_shared<queue_impl<output_value_type>>();
queue_front<output_value_type> out(out_impl);
queue_back<output_value_type> next_in(out_impl);
// Get the function's associated executor, defaulting to thread_executor.
auto ex = get_associated_executor(f, thread_executor());
// Run the function.
post(ex, [in, out, f]() mutable
{
f(in, out);
out.stop();
});
// Launch the rest of the pipeline.
return pipeline(next_in, std::move(t)...);
}
// Launch the first stage in a pipeline.
template <class F, class... Tail>
std::future<void> pipeline(F f, Tail... t)
{
// Determine the output queue type.
typedef typename executor_binder<F, thread_executor>::argument_type::value_type output_value_type;
// Create the output queue and its implementation.
auto out_impl = std::make_shared<queue_impl<output_value_type>>();
queue_front<output_value_type> out(out_impl);
queue_back<output_value_type> next_in(out_impl);
// Get the function's associated executor, defaulting to thread_executor.
auto ex = get_associated_executor(f, thread_executor());
// Run the function.
post(ex, [out, f]() mutable
{
f(out);
out.stop();
});
// Launch the rest of the pipeline.
return pipeline(next_in, std::move(t)...);
}
//------------------------------------------------------------------------------
#include <asio/thread_pool.hpp>
#include <iostream>
#include <string>
using asio::bind_executor;
using asio::thread_pool;
void reader(queue_front<std::string> out)
{
std::string line;
while (std::getline(std::cin, line))
out.push(line);
}
void filter(queue_back<std::string> in, queue_front<std::string> out)
{
std::string line;
while (in.pop(line))
if (line.length() > 5)
out.push(line);
}
void upper(queue_back<std::string> in, queue_front<std::string> out)
{
std::string line;
while (in.pop(line))
{
std::string new_line;
for (char c : line)
new_line.push_back(std::toupper(c));
out.push(new_line);
}
}
void writer(queue_back<std::string> in)
{
std::size_t count = 0;
std::string line;
while (in.pop(line))
std::cout << count++ << ": " << line << std::endl;
}
int main()
{
thread_pool pool(1);
auto f = pipeline(reader, filter, bind_executor(pool, upper), writer);
f.wait();
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/executors/priority_scheduler.cpp | #include <asio/dispatch.hpp>
#include <asio/execution_context.hpp>
#include <condition_variable>
#include <iostream>
#include <memory>
#include <mutex>
#include <queue>
using asio::dispatch;
using asio::execution_context;
namespace execution = asio::execution;
class priority_scheduler : public execution_context
{
public:
// A class that satisfies the Executor requirements.
class executor_type
{
public:
executor_type(priority_scheduler& ctx, int pri) noexcept
: context_(ctx), priority_(pri)
{
}
priority_scheduler& query(execution::context_t) const noexcept
{
return context_;
}
template <class Func>
void execute(Func f) const
{
auto p(std::make_shared<item<Func>>(priority_, std::move(f)));
std::lock_guard<std::mutex> lock(context_.mutex_);
context_.queue_.push(p);
context_.condition_.notify_one();
}
friend bool operator==(const executor_type& a,
const executor_type& b) noexcept
{
return &a.context_ == &b.context_;
}
friend bool operator!=(const executor_type& a,
const executor_type& b) noexcept
{
return &a.context_ != &b.context_;
}
private:
priority_scheduler& context_;
int priority_;
};
~priority_scheduler() noexcept
{
shutdown();
destroy();
}
executor_type get_executor(int pri = 0) noexcept
{
return executor_type(*const_cast<priority_scheduler*>(this), pri);
}
void run()
{
std::unique_lock<std::mutex> lock(mutex_);
for (;;)
{
condition_.wait(lock, [&]{ return stopped_ || !queue_.empty(); });
if (stopped_)
return;
auto p(queue_.top());
queue_.pop();
lock.unlock();
p->execute_(p);
lock.lock();
}
}
void stop()
{
std::lock_guard<std::mutex> lock(mutex_);
stopped_ = true;
condition_.notify_all();
}
private:
struct item_base
{
int priority_;
void (*execute_)(std::shared_ptr<item_base>&);
};
template <class Func>
struct item : item_base
{
item(int pri, Func f) : function_(std::move(f))
{
priority_ = pri;
execute_ = [](std::shared_ptr<item_base>& p)
{
Func tmp(std::move(static_cast<item*>(p.get())->function_));
p.reset();
tmp();
};
}
Func function_;
};
struct item_comp
{
bool operator()(
const std::shared_ptr<item_base>& a,
const std::shared_ptr<item_base>& b)
{
return a->priority_ < b->priority_;
}
};
std::mutex mutex_;
std::condition_variable condition_;
std::priority_queue<
std::shared_ptr<item_base>,
std::vector<std::shared_ptr<item_base>>,
item_comp> queue_;
bool stopped_ = false;
};
int main()
{
priority_scheduler sched;
auto low = sched.get_executor(0);
auto med = sched.get_executor(1);
auto high = sched.get_executor(2);
dispatch(low, []{ std::cout << "1\n"; });
dispatch(low, []{ std::cout << "11\n"; });
dispatch(med, []{ std::cout << "2\n"; });
dispatch(med, []{ std::cout << "22\n"; });
dispatch(high, []{ std::cout << "3\n"; });
dispatch(high, []{ std::cout << "33\n"; });
dispatch(high, []{ std::cout << "333\n"; });
dispatch(sched.get_executor(-1), [&]{ sched.stop(); });
sched.run();
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/executors/actor.cpp | #include <asio/any_io_executor.hpp>
#include <asio/defer.hpp>
#include <asio/post.hpp>
#include <asio/strand.hpp>
#include <asio/system_executor.hpp>
#include <condition_variable>
#include <deque>
#include <memory>
#include <mutex>
#include <typeinfo>
#include <vector>
using asio::any_io_executor;
using asio::defer;
using asio::post;
using asio::strand;
using asio::system_executor;
//------------------------------------------------------------------------------
// A tiny actor framework
// ~~~~~~~~~~~~~~~~~~~~~~
class actor;
// Used to identify the sender and recipient of messages.
typedef actor* actor_address;
// Base class for all registered message handlers.
class message_handler_base
{
public:
virtual ~message_handler_base() {}
// Used to determine which message handlers receive an incoming message.
virtual const std::type_info& message_id() const = 0;
};
// Base class for a handler for a specific message type.
template <class Message>
class message_handler : public message_handler_base
{
public:
// Handle an incoming message.
virtual void handle_message(Message msg, actor_address from) = 0;
};
// Concrete message handler for a specific message type.
template <class Actor, class Message>
class mf_message_handler : public message_handler<Message>
{
public:
// Construct a message handler to invoke the specified member function.
mf_message_handler(void (Actor::* mf)(Message, actor_address), Actor* a)
: function_(mf), actor_(a)
{
}
// Used to determine which message handlers receive an incoming message.
virtual const std::type_info& message_id() const
{
return typeid(Message);
}
// Handle an incoming message.
virtual void handle_message(Message msg, actor_address from)
{
(actor_->*function_)(std::move(msg), from);
}
// Determine whether the message handler represents the specified function.
bool is_function(void (Actor::* mf)(Message, actor_address)) const
{
return mf == function_;
}
private:
void (Actor::* function_)(Message, actor_address);
Actor* actor_;
};
// Base class for all actors.
class actor
{
public:
virtual ~actor()
{
}
// Obtain the actor's address for use as a message sender or recipient.
actor_address address()
{
return this;
}
// Send a message from one actor to another.
template <class Message>
friend void send(Message msg, actor_address from, actor_address to)
{
// Execute the message handler in the context of the target's executor.
post(to->executor_,
[=]
{
to->call_handler(std::move(msg), from);
});
}
protected:
// Construct the actor to use the specified executor for all message handlers.
actor(any_io_executor e)
: executor_(std::move(e))
{
}
// Register a handler for a specific message type. Duplicates are permitted.
template <class Actor, class Message>
void register_handler(void (Actor::* mf)(Message, actor_address))
{
handlers_.push_back(
std::make_shared<mf_message_handler<Actor, Message>>(
mf, static_cast<Actor*>(this)));
}
// Deregister a handler. Removes only the first matching handler.
template <class Actor, class Message>
void deregister_handler(void (Actor::* mf)(Message, actor_address))
{
const std::type_info& id = typeid(Message);
for (auto iter = handlers_.begin(); iter != handlers_.end(); ++iter)
{
if ((*iter)->message_id() == id)
{
auto mh = static_cast<mf_message_handler<Actor, Message>*>(iter->get());
if (mh->is_function(mf))
{
handlers_.erase(iter);
return;
}
}
}
}
// Send a message from within a message handler.
template <class Message>
void tail_send(Message msg, actor_address to)
{
// Execute the message handler in the context of the target's executor.
actor* from = this;
defer(to->executor_,
[=]
{
to->call_handler(std::move(msg), from);
});
}
private:
// Find the matching message handlers, if any, and call them.
template <class Message>
void call_handler(Message msg, actor_address from)
{
const std::type_info& message_id = typeid(Message);
for (auto& h: handlers_)
{
if (h->message_id() == message_id)
{
auto mh = static_cast<message_handler<Message>*>(h.get());
mh->handle_message(msg, from);
}
}
}
// All messages associated with a single actor object should be processed
// non-concurrently. We use a strand to ensure non-concurrent execution even
// if the underlying executor may use multiple threads.
strand<any_io_executor> executor_;
std::vector<std::shared_ptr<message_handler_base>> handlers_;
};
// A concrete actor that allows synchronous message retrieval.
template <class Message>
class receiver : public actor
{
public:
receiver()
: actor(system_executor())
{
register_handler(&receiver::message_handler);
}
// Block until a message has been received.
Message wait()
{
std::unique_lock<std::mutex> lock(mutex_);
condition_.wait(lock, [this]{ return !message_queue_.empty(); });
Message msg(std::move(message_queue_.front()));
message_queue_.pop_front();
return msg;
}
private:
// Handle a new message by adding it to the queue and waking a waiter.
void message_handler(Message msg, actor_address /* from */)
{
std::lock_guard<std::mutex> lock(mutex_);
message_queue_.push_back(std::move(msg));
condition_.notify_one();
}
std::mutex mutex_;
std::condition_variable condition_;
std::deque<Message> message_queue_;
};
//------------------------------------------------------------------------------
#include <asio/thread_pool.hpp>
#include <iostream>
using asio::thread_pool;
class member : public actor
{
public:
explicit member(any_io_executor e)
: actor(std::move(e))
{
register_handler(&member::init_handler);
}
private:
void init_handler(actor_address next, actor_address from)
{
next_ = next;
caller_ = from;
register_handler(&member::token_handler);
deregister_handler(&member::init_handler);
}
void token_handler(int token, actor_address /*from*/)
{
int msg(token);
actor_address to(caller_);
if (token > 0)
{
msg = token - 1;
to = next_;
}
tail_send(msg, to);
}
actor_address next_;
actor_address caller_;
};
int main()
{
const std::size_t num_threads = 16;
const int num_hops = 50000000;
const std::size_t num_actors = 503;
const int token_value = (num_hops + num_actors - 1) / num_actors;
const std::size_t actors_per_thread = num_actors / num_threads;
struct single_thread_pool : thread_pool { single_thread_pool() : thread_pool(1) {} };
single_thread_pool pools[num_threads];
std::vector<std::shared_ptr<member>> members(num_actors);
receiver<int> rcvr;
// Create the member actors.
for (std::size_t i = 0; i < num_actors; ++i)
members[i] = std::make_shared<member>(pools[(i / actors_per_thread) % num_threads].get_executor());
// Initialise the actors by passing each one the address of the next actor in the ring.
for (std::size_t i = num_actors, next_i = 0; i > 0; next_i = --i)
send(members[next_i]->address(), rcvr.address(), members[i - 1]->address());
// Send exactly one token to each actor, all with the same initial value, rounding up if required.
for (std::size_t i = 0; i < num_actors; ++i)
send(token_value, rcvr.address(), members[i]->address());
// Wait for all signal messages, indicating the tokens have all reached zero.
for (std::size_t i = 0; i < num_actors; ++i)
rcvr.wait();
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/executors/bank_account_1.cpp | #include <asio/execution.hpp>
#include <asio/static_thread_pool.hpp>
#include <iostream>
using asio::static_thread_pool;
namespace execution = asio::execution;
// Traditional active object pattern.
// Member functions do not block.
class bank_account
{
int balance_ = 0;
mutable static_thread_pool pool_{1};
public:
void deposit(int amount)
{
pool_.executor().execute(
[this, amount]
{
balance_ += amount;
});
}
void withdraw(int amount)
{
pool_.executor().execute(
[this, amount]
{
if (balance_ >= amount)
balance_ -= amount;
});
}
void print_balance() const
{
pool_.executor().execute(
[this]
{
std::cout << "balance = " << balance_ << "\n";
});
}
~bank_account()
{
pool_.wait();
}
};
int main()
{
bank_account acct;
acct.deposit(20);
acct.withdraw(10);
acct.print_balance();
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/executors/fork_join.cpp | #include <asio/execution.hpp>
#include <asio/static_thread_pool.hpp>
#include <algorithm>
#include <condition_variable>
#include <memory>
#include <mutex>
#include <queue>
#include <thread>
#include <numeric>
using asio::static_thread_pool;
namespace execution = asio::execution;
// A fixed-size thread pool used to implement fork/join semantics. Functions
// are scheduled using a simple FIFO queue. Implementing work stealing, or
// using a queue based on atomic operations, are left as tasks for the reader.
class fork_join_pool
{
public:
// The constructor starts a thread pool with the specified number of threads.
// Note that the thread_count is not a fixed limit on the pool's concurrency.
// Additional threads may temporarily be added to the pool if they join a
// fork_executor.
explicit fork_join_pool(
std::size_t thread_count = std::max(std::thread::hardware_concurrency(), 1u) * 2)
: use_count_(1),
threads_(thread_count)
{
try
{
// Ask each thread in the pool to dequeue and execute functions until
// it is time to shut down, i.e. the use count is zero.
for (thread_count_ = 0; thread_count_ < thread_count; ++thread_count_)
{
threads_.executor().execute(
[this]
{
std::unique_lock<std::mutex> lock(mutex_);
while (use_count_ > 0)
if (!execute_next(lock))
condition_.wait(lock);
});
}
}
catch (...)
{
stop_threads();
threads_.wait();
throw;
}
}
// The destructor waits for the pool to finish executing functions.
~fork_join_pool()
{
stop_threads();
threads_.wait();
}
private:
friend class fork_executor;
// The base for all functions that are queued in the pool.
struct function_base
{
std::shared_ptr<std::size_t> work_count_;
void (*execute_)(std::shared_ptr<function_base>& p);
};
// Execute the next function from the queue, if any. Returns true if a
// function was executed, and false if the queue was empty.
bool execute_next(std::unique_lock<std::mutex>& lock)
{
if (queue_.empty())
return false;
auto p(queue_.front());
queue_.pop();
lock.unlock();
execute(lock, p);
return true;
}
// Execute a function and decrement the outstanding work.
void execute(std::unique_lock<std::mutex>& lock,
std::shared_ptr<function_base>& p)
{
std::shared_ptr<std::size_t> work_count(std::move(p->work_count_));
try
{
p->execute_(p);
lock.lock();
do_work_finished(work_count);
}
catch (...)
{
lock.lock();
do_work_finished(work_count);
throw;
}
}
// Increment outstanding work.
void do_work_started(const std::shared_ptr<std::size_t>& work_count) noexcept
{
if (++(*work_count) == 1)
++use_count_;
}
// Decrement outstanding work. Notify waiting threads if we run out.
void do_work_finished(const std::shared_ptr<std::size_t>& work_count) noexcept
{
if (--(*work_count) == 0)
{
--use_count_;
condition_.notify_all();
}
}
// Dispatch a function, executing it immediately if the queue is already
// loaded. Otherwise adds the function to the queue and wakes a thread.
void do_execute(std::shared_ptr<function_base> p,
const std::shared_ptr<std::size_t>& work_count)
{
std::unique_lock<std::mutex> lock(mutex_);
if (queue_.size() > thread_count_ * 16)
{
do_work_started(work_count);
lock.unlock();
execute(lock, p);
}
else
{
queue_.push(p);
do_work_started(work_count);
condition_.notify_one();
}
}
// Ask all threads to shut down.
void stop_threads()
{
std::lock_guard<std::mutex> lock(mutex_);
--use_count_;
condition_.notify_all();
}
std::mutex mutex_;
std::condition_variable condition_;
std::queue<std::shared_ptr<function_base>> queue_;
std::size_t use_count_;
std::size_t thread_count_;
static_thread_pool threads_;
};
// A class that satisfies the Executor requirements. Every function or piece of
// work associated with a fork_executor is part of a single, joinable group.
class fork_executor
{
public:
fork_executor(fork_join_pool& ctx)
: context_(ctx),
work_count_(std::make_shared<std::size_t>(0))
{
}
fork_join_pool& query(execution::context_t) const noexcept
{
return context_;
}
template <class Func>
void execute(Func f) const
{
auto p(std::make_shared<function<Func>>(std::move(f), work_count_));
context_.do_execute(p, work_count_);
}
friend bool operator==(const fork_executor& a,
const fork_executor& b) noexcept
{
return a.work_count_ == b.work_count_;
}
friend bool operator!=(const fork_executor& a,
const fork_executor& b) noexcept
{
return a.work_count_ != b.work_count_;
}
// Block until all work associated with the executor is complete. While it is
// waiting, the thread may be borrowed to execute functions from the queue.
void join() const
{
std::unique_lock<std::mutex> lock(context_.mutex_);
while (*work_count_ > 0)
if (!context_.execute_next(lock))
context_.condition_.wait(lock);
}
private:
template <class Func>
struct function : fork_join_pool::function_base
{
explicit function(Func f, const std::shared_ptr<std::size_t>& w)
: function_(std::move(f))
{
work_count_ = w;
execute_ = [](std::shared_ptr<fork_join_pool::function_base>& p)
{
Func tmp(std::move(static_cast<function*>(p.get())->function_));
p.reset();
tmp();
};
}
Func function_;
};
fork_join_pool& context_;
std::shared_ptr<std::size_t> work_count_;
};
// Helper class to automatically join a fork_executor when exiting a scope.
class join_guard
{
public:
explicit join_guard(const fork_executor& ex) : ex_(ex) {}
join_guard(const join_guard&) = delete;
join_guard(join_guard&&) = delete;
~join_guard() { ex_.join(); }
private:
fork_executor ex_;
};
//------------------------------------------------------------------------------
#include <algorithm>
#include <iostream>
#include <random>
#include <vector>
fork_join_pool pool;
template <class Iterator>
void fork_join_sort(Iterator begin, Iterator end)
{
std::size_t n = end - begin;
if (n > 32768)
{
{
fork_executor fork(pool);
join_guard join(fork);
fork.execute([=]{ fork_join_sort(begin, begin + n / 2); });
fork.execute([=]{ fork_join_sort(begin + n / 2, end); });
}
std::inplace_merge(begin, begin + n / 2, end);
}
else
{
std::sort(begin, end);
}
}
int main(int argc, char* argv[])
{
if (argc != 2)
{
std::cerr << "Usage: fork_join <size>\n";
return 1;
}
std::vector<double> vec(std::atoll(argv[1]));
std::iota(vec.begin(), vec.end(), 0);
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(vec.begin(), vec.end(), g);
std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
fork_join_sort(vec.begin(), vec.end());
std::chrono::steady_clock::duration elapsed = std::chrono::steady_clock::now() - start;
std::cout << "sort took ";
std::cout << std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count();
std::cout << " microseconds" << std::endl;
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/timeouts/async_tcp_client.cpp | //
// async_tcp_client.cpp
// ~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 "asio/buffer.hpp"
#include "asio/io_context.hpp"
#include "asio/ip/tcp.hpp"
#include "asio/read_until.hpp"
#include "asio/steady_timer.hpp"
#include "asio/write.hpp"
#include <functional>
#include <iostream>
#include <string>
using asio::steady_timer;
using asio::ip::tcp;
using std::placeholders::_1;
using std::placeholders::_2;
//
// 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
// to message sending.
//
class client
{
public:
client(asio::io_context& io_context)
: socket_(io_context),
deadline_(io_context),
heartbeat_timer_(io_context)
{
}
// Called by the user of the client class to initiate the connection process.
// The endpoints will have been obtained using a tcp::resolver.
void start(tcp::resolver::results_type endpoints)
{
// Start the connect actor.
endpoints_ = endpoints;
start_connect(endpoints_.begin());
// 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(std::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;
std::error_code ignored_error;
socket_.close(ignored_error);
deadline_.cancel();
heartbeat_timer_.cancel();
}
private:
void start_connect(tcp::resolver::results_type::iterator endpoint_iter)
{
if (endpoint_iter != endpoints_.end())
{
std::cout << "Trying " << endpoint_iter->endpoint() << "...\n";
// Set a deadline for the connect operation.
deadline_.expires_after(std::chrono::seconds(60));
// Start the asynchronous connect operation.
socket_.async_connect(endpoint_iter->endpoint(),
std::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 std::error_code& error,
tcp::resolver::results_type::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 (error)
{
std::cout << "Connect error: " << error.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_after(std::chrono::seconds(30));
// Start an asynchronous operation to read a newline-delimited message.
asio::async_read_until(socket_,
asio::dynamic_buffer(input_buffer_), '\n',
std::bind(&client::handle_read, this, _1, _2));
}
void handle_read(const std::error_code& error, std::size_t n)
{
if (stopped_)
return;
if (!error)
{
// Extract the newline-delimited message from the buffer.
std::string line(input_buffer_.substr(0, n - 1));
input_buffer_.erase(0, n);
// Empty messages are heartbeats and so ignored.
if (!line.empty())
{
std::cout << "Received: " << line << "\n";
}
start_read();
}
else
{
std::cout << "Error on receive: " << error.message() << "\n";
stop();
}
}
void start_write()
{
if (stopped_)
return;
// Start an asynchronous operation to send a heartbeat message.
asio::async_write(socket_, asio::buffer("\n", 1),
std::bind(&client::handle_write, this, _1));
}
void handle_write(const std::error_code& error)
{
if (stopped_)
return;
if (!error)
{
// Wait 10 seconds before sending the next heartbeat.
heartbeat_timer_.expires_after(std::chrono::seconds(10));
heartbeat_timer_.async_wait(std::bind(&client::start_write, this));
}
else
{
std::cout << "Error on heartbeat: " << error.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_.expiry() <= steady_timer::clock_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 the
// maximum time point so that the actor takes no action until a new
// deadline is set.
deadline_.expires_at(steady_timer::time_point::max());
}
// Put the actor back to sleep.
deadline_.async_wait(std::bind(&client::check_deadline, this));
}
private:
bool stopped_ = false;
tcp::resolver::results_type endpoints_;
tcp::socket socket_;
std::string input_buffer_;
steady_timer deadline_;
steady_timer heartbeat_timer_;
};
int main(int argc, char* argv[])
{
try
{
if (argc != 3)
{
std::cerr << "Usage: client <host> <port>\n";
return 1;
}
asio::io_context io_context;
tcp::resolver r(io_context);
client c(io_context);
c.start(r.resolve(argv[1], argv[2]));
io_context.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/timeouts/blocking_tcp_client.cpp | //
// blocking_tcp_client.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 "asio/buffer.hpp"
#include "asio/connect.hpp"
#include "asio/io_context.hpp"
#include "asio/ip/tcp.hpp"
#include "asio/read_until.hpp"
#include "asio/system_error.hpp"
#include "asio/write.hpp"
#include <cstdlib>
#include <iostream>
#include <string>
using asio::ip::tcp;
//----------------------------------------------------------------------
//
// This class manages socket timeouts by running the io_context using the timed
// io_context::run_for() member function. Each asynchronous operation is given
// a timeout within which it must complete. The socket operations themselves
// use lambdas as completion handlers. For a given socket operation, the client
// object runs the io_context to block thread execution until the operation
// completes or the timeout is reached. If the io_context::run_for() function
// times out, the socket is closed and the outstanding asynchronous operation
// is cancelled.
//
class client
{
public:
void connect(const std::string& host, const std::string& service,
std::chrono::steady_clock::duration timeout)
{
// Resolve the host name and service to a list of endpoints.
auto endpoints = tcp::resolver(io_context_).resolve(host, service);
// Start the asynchronous operation itself. The lambda that is used as a
// callback will update the error variable when the operation completes.
// The blocking_udp_client.cpp example shows how you can use std::bind
// rather than a lambda.
std::error_code error;
asio::async_connect(socket_, endpoints,
[&](const std::error_code& result_error,
const tcp::endpoint& /*result_endpoint*/)
{
error = result_error;
});
// Run the operation until it completes, or until the timeout.
run(timeout);
// Determine whether a connection was successfully established.
if (error)
throw std::system_error(error);
}
std::string read_line(std::chrono::steady_clock::duration timeout)
{
// Start the asynchronous operation. The lambda that is used as a callback
// will update the error and n variables when the operation completes. The
// blocking_udp_client.cpp example shows how you can use std::bind rather
// than a lambda.
std::error_code error;
std::size_t n = 0;
asio::async_read_until(socket_,
asio::dynamic_buffer(input_buffer_), '\n',
[&](const std::error_code& result_error,
std::size_t result_n)
{
error = result_error;
n = result_n;
});
// Run the operation until it completes, or until the timeout.
run(timeout);
// Determine whether the read completed successfully.
if (error)
throw std::system_error(error);
std::string line(input_buffer_.substr(0, n - 1));
input_buffer_.erase(0, n);
return line;
}
void write_line(const std::string& line,
std::chrono::steady_clock::duration timeout)
{
std::string data = line + "\n";
// Start the asynchronous operation itself. The lambda that is used as a
// callback will update the error variable when the operation completes.
// The blocking_udp_client.cpp example shows how you can use std::bind
// rather than a lambda.
std::error_code error;
asio::async_write(socket_, asio::buffer(data),
[&](const std::error_code& result_error,
std::size_t /*result_n*/)
{
error = result_error;
});
// Run the operation until it completes, or until the timeout.
run(timeout);
// Determine whether the read completed successfully.
if (error)
throw std::system_error(error);
}
private:
void run(std::chrono::steady_clock::duration timeout)
{
// Restart the io_context, as it may have been left in the "stopped" state
// by a previous operation.
io_context_.restart();
// Block until the asynchronous operation has completed, or timed out. If
// the pending asynchronous operation is a composed operation, the deadline
// applies to the entire operation, rather than individual operations on
// the socket.
io_context_.run_for(timeout);
// If the asynchronous operation completed successfully then the io_context
// would have been stopped due to running out of work. If it was not
// stopped, then the io_context::run_for call must have timed out.
if (!io_context_.stopped())
{
// Close the socket to cancel the outstanding asynchronous operation.
socket_.close();
// Run the io_context again until the operation completes.
io_context_.run();
}
}
asio::io_context io_context_;
tcp::socket socket_{io_context_};
std::string input_buffer_;
};
//----------------------------------------------------------------------
int main(int argc, char* argv[])
{
try
{
if (argc != 4)
{
std::cerr << "Usage: blocking_tcp_client <host> <port> <message>\n";
return 1;
}
client c;
c.connect(argv[1], argv[2], std::chrono::seconds(10));
auto time_sent = std::chrono::steady_clock::now();
c.write_line(argv[3], std::chrono::seconds(10));
for (;;)
{
std::string line = c.read_line(std::chrono::seconds(10));
// Keep going until we get back the line that was sent.
if (line == argv[3])
break;
}
auto time_received = std::chrono::steady_clock::now();
std::cout << "Round trip time: ";
std::cout << std::chrono::duration_cast<
std::chrono::microseconds>(
time_received - time_sent).count();
std::cout << " microseconds\n";
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/timeouts/server.cpp | //
// server.cpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <algorithm>
#include <cstdlib>
#include <deque>
#include <iostream>
#include <memory>
#include <set>
#include <string>
#include "asio/buffer.hpp"
#include "asio/io_context.hpp"
#include "asio/ip/tcp.hpp"
#include "asio/ip/udp.hpp"
#include "asio/read_until.hpp"
#include "asio/steady_timer.hpp"
#include "asio/write.hpp"
using asio::steady_timer;
using asio::ip::tcp;
using asio::ip::udp;
//----------------------------------------------------------------------
class subscriber
{
public:
virtual ~subscriber() = default;
virtual void deliver(const std::string& msg) = 0;
};
typedef std::shared_ptr<subscriber> subscriber_ptr;
//----------------------------------------------------------------------
class channel
{
public:
void join(subscriber_ptr subscriber)
{
subscribers_.insert(subscriber);
}
void leave(subscriber_ptr subscriber)
{
subscribers_.erase(subscriber);
}
void deliver(const std::string& msg)
{
for (const auto& s : subscribers_)
{
s->deliver(msg);
}
}
private:
std::set<subscriber_ptr> subscribers_;
};
//----------------------------------------------------------------------
//
// 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 two "actors" that persist for the lifetime of the
// session object, one for input and one for output:
//
// +----------------+ +----------------+
// | | | |
// | check_deadline |<-------+ | check_deadline |<-------+
// | | | | | |
// +----------------+ | +----------------+ |
// | | | |
// async_wait() | +----------------+ async_wait() | +----------------+
// on input | | lambda | on output | | lambda |
// deadline +--->| in | deadline +--->| in |
// | check_deadline | | check_deadline |
// +----------------+ +----------------+
//
// If either deadline actor determines that the corresponding deadline has
// expired, the socket is closed and any outstanding operations are cancelled.
//
// The input actor reads messages from the socket, where messages are delimited
// by the newline character:
//
// +-------------+
// | |
// | read_line |<----+
// | | |
// +-------------+ |
// | |
// async_- | +-------------+
// read_- | | lambda |
// until() +--->| in |
// | read_line |
// +-------------+
//
// The deadline for receiving a complete message is 30 seconds. If a non-empty
// message is received, it is delivered to all subscribers. If a heartbeat (a
// message that consists of a single newline character) is received, a heartbeat
// is enqueued for the client, provided there are no other messages waiting to
// be sent.
//
// The output actor is responsible for sending messages to the client:
//
// +----------------+
// | |<---------------------+
// | await_output | |
// | |<-------+ |
// +----------------+ | |
// | | | |
// | async_- | +----------------+ |
// | wait() | | lambda | |
// | +->| in | |
// | | await_output | |
// | +----------------+ |
// V |
// +--------------+ +--------------+
// | | async_write() | lambda |
// | write_line |-------------->| in |
// | | | write_line |
// +--------------+ +--------------+
//
// The output actor first waits for an output message to be enqueued. It does
// this by using a steady_timer as an asynchronous condition variable. The
// steady_timer will be signalled whenever the output queue is non-empty.
//
// Once a message is available, it is sent to the client. The deadline for
// sending a complete message is 30 seconds. After the message is successfully
// sent, the output actor again waits for the output queue to become non-empty.
//
class tcp_session
: public subscriber,
public std::enable_shared_from_this<tcp_session>
{
public:
tcp_session(tcp::socket socket, channel& ch)
: channel_(ch),
socket_(std::move(socket))
{
input_deadline_.expires_at(steady_timer::time_point::max());
output_deadline_.expires_at(steady_timer::time_point::max());
// The non_empty_output_queue_ steady_timer is set to the maximum time
// point whenever the output queue is empty. This ensures that the output
// actor stays asleep until a message is put into the queue.
non_empty_output_queue_.expires_at(steady_timer::time_point::max());
}
// Called by the server object to initiate the four actors.
void start()
{
channel_.join(shared_from_this());
read_line();
check_deadline(input_deadline_);
await_output();
check_deadline(output_deadline_);
}
private:
void stop()
{
channel_.leave(shared_from_this());
std::error_code ignored_error;
socket_.close(ignored_error);
input_deadline_.cancel();
non_empty_output_queue_.cancel();
output_deadline_.cancel();
}
bool stopped() const
{
return !socket_.is_open();
}
void deliver(const std::string& msg) override
{
output_queue_.push_back(msg + "\n");
// Signal that the output queue contains messages. Modifying the expiry
// will wake the output actor, if it is waiting on the timer.
non_empty_output_queue_.expires_at(steady_timer::time_point::min());
}
void read_line()
{
// Set a deadline for the read operation.
input_deadline_.expires_after(std::chrono::seconds(30));
// Start an asynchronous operation to read a newline-delimited message.
auto self(shared_from_this());
asio::async_read_until(socket_,
asio::dynamic_buffer(input_buffer_), '\n',
[this, self](const std::error_code& error, std::size_t n)
{
// Check if the session was stopped while the operation was pending.
if (stopped())
return;
if (!error)
{
// Extract the newline-delimited message from the buffer.
std::string msg(input_buffer_.substr(0, n - 1));
input_buffer_.erase(0, n);
if (!msg.empty())
{
channel_.deliver(msg);
}
else
{
// We received a heartbeat message from the client. If there's
// nothing else being sent or ready to be sent, send a heartbeat
// right back.
if (output_queue_.empty())
{
output_queue_.push_back("\n");
// Signal that the output queue contains messages. Modifying
// the expiry will wake the output actor, if it is waiting on
// the timer.
non_empty_output_queue_.expires_at(
steady_timer::time_point::min());
}
}
read_line();
}
else
{
stop();
}
});
}
void await_output()
{
auto self(shared_from_this());
non_empty_output_queue_.async_wait(
[this, self](const std::error_code& /*error*/)
{
// Check if the session was stopped while the operation was pending.
if (stopped())
return;
if (output_queue_.empty())
{
// There are no messages that are ready to be sent. The actor goes
// to sleep by waiting on the non_empty_output_queue_ timer. When a
// new message is added, the timer will be modified and the actor
// will wake.
non_empty_output_queue_.expires_at(steady_timer::time_point::max());
await_output();
}
else
{
write_line();
}
});
}
void write_line()
{
// Set a deadline for the write operation.
output_deadline_.expires_after(std::chrono::seconds(30));
// Start an asynchronous operation to send a message.
auto self(shared_from_this());
asio::async_write(socket_,
asio::buffer(output_queue_.front()),
[this, self](const std::error_code& error, std::size_t /*n*/)
{
// Check if the session was stopped while the operation was pending.
if (stopped())
return;
if (!error)
{
output_queue_.pop_front();
await_output();
}
else
{
stop();
}
});
}
void check_deadline(steady_timer& deadline)
{
auto self(shared_from_this());
deadline.async_wait(
[this, self, &deadline](const std::error_code& /*error*/)
{
// Check if the session was stopped while the operation was pending.
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.expiry() <= steady_timer::clock_type::now())
{
// The deadline has passed. Stop the session. The other actors will
// terminate as soon as possible.
stop();
}
else
{
// Put the actor back to sleep.
check_deadline(deadline);
}
});
}
channel& channel_;
tcp::socket socket_;
std::string input_buffer_;
steady_timer input_deadline_{socket_.get_executor()};
std::deque<std::string> output_queue_;
steady_timer non_empty_output_queue_{socket_.get_executor()};
steady_timer output_deadline_{socket_.get_executor()};
};
typedef std::shared_ptr<tcp_session> tcp_session_ptr;
//----------------------------------------------------------------------
class udp_broadcaster
: public subscriber
{
public:
udp_broadcaster(asio::io_context& io_context,
const udp::endpoint& broadcast_endpoint)
: socket_(io_context)
{
socket_.connect(broadcast_endpoint);
socket_.set_option(udp::socket::broadcast(true));
}
private:
void deliver(const std::string& msg)
{
std::error_code ignored_error;
socket_.send(asio::buffer(msg), 0, ignored_error);
}
udp::socket socket_;
};
//----------------------------------------------------------------------
class server
{
public:
server(asio::io_context& io_context,
const tcp::endpoint& listen_endpoint,
const udp::endpoint& broadcast_endpoint)
: io_context_(io_context),
acceptor_(io_context, listen_endpoint)
{
channel_.join(
std::make_shared<udp_broadcaster>(
io_context_, broadcast_endpoint));
accept();
}
private:
void accept()
{
acceptor_.async_accept(
[this](const std::error_code& error, tcp::socket socket)
{
if (!error)
{
std::make_shared<tcp_session>(std::move(socket), channel_)->start();
}
accept();
});
}
asio::io_context& io_context_;
tcp::acceptor acceptor_;
channel channel_;
};
//----------------------------------------------------------------------
int main(int argc, char* argv[])
{
try
{
using namespace std; // For atoi.
if (argc != 4)
{
std::cerr << "Usage: server <listen_port> <bcast_address> <bcast_port>\n";
return 1;
}
asio::io_context io_context;
tcp::endpoint listen_endpoint(tcp::v4(), atoi(argv[1]));
udp::endpoint broadcast_endpoint(
asio::ip::make_address(argv[2]), atoi(argv[3]));
server s(io_context, listen_endpoint, broadcast_endpoint);
io_context.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/timeouts/blocking_udp_client.cpp | //
// blocking_udp_client.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 "asio/buffer.hpp"
#include "asio/io_context.hpp"
#include "asio/ip/udp.hpp"
#include <cstdlib>
#include <functional>
#include <iostream>
using asio::ip::udp;
using std::placeholders::_1;
using std::placeholders::_2;
//----------------------------------------------------------------------
//
// This class manages socket timeouts by running the io_context using the timed
// io_context::run_for() member function. Each asynchronous operation is given
// a timeout within which it must complete. The socket operations themselves
// use std::bind to specify the completion handler:
//
// +---------------+
// | |
// | receive |
// | |
// +---------------+
// |
// async_- | +----------------+
// receive() | | |
// +--->| handle_receive |
// | |
// +----------------+
//
// For a given socket operation, the client object runs the io_context to block
// thread execution until the operation completes or the timeout is reached. If
// the io_context::run_for() function times out, the socket is closed and the
// outstanding asynchronous operation is cancelled.
//
class client
{
public:
client(const udp::endpoint& listen_endpoint)
: socket_(io_context_, listen_endpoint)
{
}
std::size_t receive(const asio::mutable_buffer& buffer,
std::chrono::steady_clock::duration timeout,
std::error_code& error)
{
// Start the asynchronous operation. The handle_receive function used as a
// callback will update the error and length variables.
std::size_t length = 0;
socket_.async_receive(asio::buffer(buffer),
std::bind(&client::handle_receive, _1, _2, &error, &length));
// Run the operation until it completes, or until the timeout.
run(timeout);
return length;
}
private:
void run(std::chrono::steady_clock::duration timeout)
{
// Restart the io_context, as it may have been left in the "stopped" state
// by a previous operation.
io_context_.restart();
// Block until the asynchronous operation has completed, or timed out. If
// the pending asynchronous operation is a composed operation, the deadline
// applies to the entire operation, rather than individual operations on
// the socket.
io_context_.run_for(timeout);
// If the asynchronous operation completed successfully then the io_context
// would have been stopped due to running out of work. If it was not
// stopped, then the io_context::run_for call must have timed out.
if (!io_context_.stopped())
{
// Cancel the outstanding asynchronous operation.
socket_.cancel();
// Run the io_context again until the operation completes.
io_context_.run();
}
}
static void handle_receive(
const std::error_code& error, std::size_t length,
std::error_code* out_error, std::size_t* out_length)
{
*out_error = error;
*out_length = length;
}
private:
asio::io_context io_context_;
udp::socket socket_;
};
//----------------------------------------------------------------------
int main(int argc, char* argv[])
{
try
{
using namespace std; // For atoi.
if (argc != 3)
{
std::cerr << "Usage: blocking_udp_client <listen_addr> <listen_port>\n";
return 1;
}
udp::endpoint listen_endpoint(
asio::ip::make_address(argv[1]),
std::atoi(argv[2]));
client c(listen_endpoint);
for (;;)
{
char data[1024];
std::error_code error;
std::size_t n = c.receive(asio::buffer(data),
std::chrono::seconds(10), error);
if (error)
{
std::cout << "Receive error: " << error.message() << "\n";
}
else
{
std::cout << "Received: ";
std::cout.write(data, n);
std::cout << "\n";
}
}
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/timeouts/blocking_token_tcp_client.cpp | //
// blocking_token_tcp_client.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 "asio/connect.hpp"
#include "asio/io_context.hpp"
#include "asio/ip/tcp.hpp"
#include "asio/read_until.hpp"
#include "asio/streambuf.hpp"
#include "asio/system_error.hpp"
#include "asio/write.hpp"
#include <cstdlib>
#include <iostream>
#include <memory>
#include <string>
using asio::ip::tcp;
// NOTE: This example uses the new form of the asio::async_result trait.
// For an example that works with the Networking TS style of completion tokens,
// please see an older version of asio.
// We will use our sockets only with an io_context.
using tcp_socket = asio::basic_stream_socket<
tcp, asio::io_context::executor_type>;
//----------------------------------------------------------------------
// A custom completion token that makes asynchronous operations behave as
// though they are blocking calls with a timeout.
struct close_after
{
close_after(std::chrono::steady_clock::duration t, tcp_socket& s)
: timeout_(t), socket_(s)
{
}
// The maximum time to wait for an asynchronous operation to complete.
std::chrono::steady_clock::duration timeout_;
// The socket to be closed if the operation does not complete in time.
tcp_socket& socket_;
};
namespace asio {
// The async_result template is specialised to allow the close_after token to
// be used with asynchronous operations that have a completion signature of
// void(error_code, T). Generalising this for all completion signature forms is
// left as an exercise for the reader.
template <typename T>
class async_result<close_after, void(std::error_code, T)>
{
public:
// The initiate() function is used to launch the asynchronous operation by
// calling the operation's initiation function object. For the close_after
// completion token, we use this function to run the io_context until the
// operation is complete.
template <typename Init, typename... Args>
static T initiate(Init init, close_after token, Args&&... args)
{
asio::io_context& io_context = asio::query(
token.socket_.get_executor(), asio::execution::context);
// Call the operation's initiation function object to start the operation.
// A lambda is supplied as the completion handler, to be called when the
// operation completes.
std::error_code error;
T result;
init([&](std::error_code e, T t)
{
error = e;
result = t;
}, std::forward<Args>(args)...);
// Restart the io_context, as it may have been left in the "stopped" state
// by a previous operation.
io_context.restart();
// Block until the asynchronous operation has completed, or timed out. If
// the pending asynchronous operation is a composed operation, the deadline
// applies to the entire operation, rather than individual operations on
// the socket.
io_context.run_for(token.timeout_);
// If the asynchronous operation completed successfully then the io_context
// would have been stopped due to running out of work. If it was not
// stopped, then the io_context::run_for call must have timed out and the
// operation is still incomplete.
if (!io_context.stopped())
{
// Close the socket to cancel the outstanding asynchronous operation.
token.socket_.close();
// Run the io_context again until the operation completes.
io_context.run();
}
// If the operation failed, throw an exception. Otherwise return the result.
return error ? throw std::system_error(error) : result;
}
};
} // namespace asio
//----------------------------------------------------------------------
int main(int argc, char* argv[])
{
try
{
if (argc != 4)
{
std::cerr << "Usage: blocking_tcp_client <host> <port> <message>\n";
return 1;
}
asio::io_context io_context;
// Resolve the host name and service to a list of endpoints.
auto endpoints = tcp::resolver(io_context).resolve(argv[1], argv[2]);
tcp_socket socket(io_context);
// Run an asynchronous connect operation with a timeout.
asio::async_connect(socket, endpoints,
close_after(std::chrono::seconds(10), socket));
auto time_sent = std::chrono::steady_clock::now();
// Run an asynchronous write operation with a timeout.
std::string msg = argv[3] + std::string("\n");
asio::async_write(socket, asio::buffer(msg),
close_after(std::chrono::seconds(10), socket));
for (std::string input_buffer;;)
{
// Run an asynchronous read operation with a timeout.
std::size_t n = asio::async_read_until(socket,
asio::dynamic_buffer(input_buffer), '\n',
close_after(std::chrono::seconds(10), socket));
std::string line(input_buffer.substr(0, n - 1));
input_buffer.erase(0, n);
// Keep going until we get back the line that was sent.
if (line == argv[3])
break;
}
auto time_received = std::chrono::steady_clock::now();
std::cout << "Round trip time: ";
std::cout << std::chrono::duration_cast<
std::chrono::microseconds>(
time_received - time_sent).count();
std::cout << " microseconds\n";
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/porthopper/protocol.hpp | //
// protocol.hpp
// ~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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)
//
#ifndef PORTHOPPER_PROTOCOL_HPP
#define PORTHOPPER_PROTOCOL_HPP
#include <asio.hpp>
#include <array>
#include <cstring>
#include <iomanip>
#include <string>
#include <strstream>
// This request is sent by the client to the server over a TCP connection.
// The client uses it to perform three functions:
// - To request that data start being sent to a given port.
// - To request that data is no longer sent to a given port.
// - To change the target port to another.
class control_request
{
public:
// Construct an empty request. Used when receiving.
control_request()
{
}
// Create a request to start sending data to a given port.
static const control_request start(unsigned short port)
{
return control_request(0, port);
}
// Create a request to stop sending data to a given port.
static const control_request stop(unsigned short port)
{
return control_request(port, 0);
}
// Create a request to change the port that data is sent to.
static const control_request change(
unsigned short old_port, unsigned short new_port)
{
return control_request(old_port, new_port);
}
// Get the old port. Returns 0 for start requests.
unsigned short old_port() const
{
std::istrstream is(data_, encoded_port_size);
unsigned short port = 0;
is >> std::setw(encoded_port_size) >> std::hex >> port;
return port;
}
// Get the new port. Returns 0 for stop requests.
unsigned short new_port() const
{
std::istrstream is(data_ + encoded_port_size, encoded_port_size);
unsigned short port = 0;
is >> std::setw(encoded_port_size) >> std::hex >> port;
return port;
}
// Obtain buffers for reading from or writing to a socket.
std::array<asio::mutable_buffer, 1> to_buffers()
{
std::array<asio::mutable_buffer, 1> buffers
= { { asio::buffer(data_) } };
return buffers;
}
private:
// Construct with specified old and new ports.
control_request(unsigned short old_port_number,
unsigned short new_port_number)
{
std::ostrstream os(data_, control_request_size);
os << std::setw(encoded_port_size) << std::hex << old_port_number;
os << std::setw(encoded_port_size) << std::hex << new_port_number;
}
// The length in bytes of a control_request and its components.
enum
{
encoded_port_size = 4, // 16-bit port in hex.
control_request_size = encoded_port_size * 2
};
// The encoded request data.
char data_[control_request_size];
};
// This frame is sent from the server to subscribed clients over UDP.
class frame
{
public:
// The maximum allowable length of the payload.
enum { payload_size = 32 };
// Construct an empty frame. Used when receiving.
frame()
{
}
// Construct a frame with specified frame number and payload.
frame(unsigned long frame_number, const std::string& payload_data)
{
std::ostrstream os(data_, frame_size);
os << std::setw(encoded_number_size) << std::hex << frame_number;
os << std::setw(payload_size)
<< std::setfill(' ') << payload_data.substr(0, payload_size);
}
// Get the frame number.
unsigned long number() const
{
std::istrstream is(data_, encoded_number_size);
unsigned long frame_number = 0;
is >> std::setw(encoded_number_size) >> std::hex >> frame_number;
return frame_number;
}
// Get the payload data.
const std::string payload() const
{
return std::string(data_ + encoded_number_size, payload_size);
}
// Obtain buffers for reading from or writing to a socket.
std::array<asio::mutable_buffer, 1> to_buffers()
{
std::array<asio::mutable_buffer, 1> buffers
= { { asio::buffer(data_) } };
return buffers;
}
private:
// The length in bytes of a frame and its components.
enum
{
encoded_number_size = 8, // Frame number in hex.
frame_size = encoded_number_size + payload_size
};
// The encoded frame data.
char data_[frame_size];
};
#endif // PORTHOPPER_PROTOCOL_HPP
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/porthopper/server.cpp | //
// server.cpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio.hpp>
#include <cmath>
#include <cstdlib>
#include <exception>
#include <functional>
#include <iostream>
#include <memory>
#include <set>
#include "protocol.hpp"
using asio::ip::tcp;
using asio::ip::udp;
typedef std::shared_ptr<tcp::socket> tcp_socket_ptr;
typedef std::shared_ptr<asio::steady_timer> timer_ptr;
typedef std::shared_ptr<control_request> control_request_ptr;
class server
{
public:
// Construct the server to wait for incoming control connections.
server(asio::io_context& io_context, unsigned short port)
: acceptor_(io_context, tcp::endpoint(tcp::v4(), port)),
timer_(io_context),
udp_socket_(io_context, udp::endpoint(udp::v4(), 0)),
next_frame_number_(1)
{
// Start waiting for a new control connection.
tcp_socket_ptr new_socket(new tcp::socket(acceptor_.get_executor()));
acceptor_.async_accept(*new_socket,
std::bind(&server::handle_accept, this,
asio::placeholders::error, new_socket));
// Start the timer used to generate outgoing frames.
timer_.expires_after(asio::chrono::milliseconds(100));
timer_.async_wait(std::bind(&server::handle_timer, this));
}
// Handle a new control connection.
void handle_accept(const std::error_code& ec, tcp_socket_ptr socket)
{
if (!ec)
{
// Start receiving control requests on the connection.
control_request_ptr request(new control_request);
asio::async_read(*socket, request->to_buffers(),
std::bind(&server::handle_control_request, this,
asio::placeholders::error, socket, request));
}
// Start waiting for a new control connection.
tcp_socket_ptr new_socket(new tcp::socket(acceptor_.get_executor()));
acceptor_.async_accept(*new_socket,
std::bind(&server::handle_accept, this,
asio::placeholders::error, new_socket));
}
// Handle a new control request.
void handle_control_request(const std::error_code& ec,
tcp_socket_ptr socket, control_request_ptr request)
{
if (!ec)
{
// Delay handling of the control request to simulate network latency.
timer_ptr delay_timer(
new asio::steady_timer(acceptor_.get_executor()));
delay_timer->expires_after(asio::chrono::seconds(2));
delay_timer->async_wait(
std::bind(&server::handle_control_request_timer, this,
socket, request, delay_timer));
}
}
void handle_control_request_timer(tcp_socket_ptr socket,
control_request_ptr request, timer_ptr /*delay_timer*/)
{
// Determine what address this client is connected from, since
// subscriptions must be stored on the server as a complete endpoint, not
// just a port. We use the non-throwing overload of remote_endpoint() since
// it may fail if the socket is no longer connected.
std::error_code ec;
tcp::endpoint remote_endpoint = socket->remote_endpoint(ec);
if (!ec)
{
// Remove old port subscription, if any.
if (unsigned short old_port = request->old_port())
{
udp::endpoint old_endpoint(remote_endpoint.address(), old_port);
subscribers_.erase(old_endpoint);
std::cout << "Removing subscription " << old_endpoint << std::endl;
}
// Add new port subscription, if any.
if (unsigned short new_port = request->new_port())
{
udp::endpoint new_endpoint(remote_endpoint.address(), new_port);
subscribers_.insert(new_endpoint);
std::cout << "Adding subscription " << new_endpoint << std::endl;
}
}
// Wait for next control request on this connection.
asio::async_read(*socket, request->to_buffers(),
std::bind(&server::handle_control_request, this,
asio::placeholders::error, socket, request));
}
// Every time the timer fires we will generate a new frame and send it to all
// subscribers.
void handle_timer()
{
// Generate payload.
double x = next_frame_number_ * 0.2;
double y = std::sin(x);
int char_index = static_cast<int>((y + 1.0) * (frame::payload_size / 2));
std::string payload;
for (int i = 0; i < frame::payload_size; ++i)
payload += (i == char_index ? '*' : '.');
// Create the frame to be sent to all subscribers.
frame f(next_frame_number_++, payload);
// Send frame to all subscribers. We can use synchronous calls here since
// UDP send operations typically do not block.
std::set<udp::endpoint>::iterator j;
for (j = subscribers_.begin(); j != subscribers_.end(); ++j)
{
std::error_code ec;
udp_socket_.send_to(f.to_buffers(), *j, 0, ec);
}
// Wait for next timeout.
timer_.expires_after(asio::chrono::milliseconds(100));
timer_.async_wait(std::bind(&server::handle_timer, this));
}
private:
// The acceptor used to accept incoming control connections.
tcp::acceptor acceptor_;
// The timer used for generating data.
asio::steady_timer timer_;
// The socket used to send data to subscribers.
udp::socket udp_socket_;
// The next frame number.
unsigned long next_frame_number_;
// The set of endpoints that are subscribed.
std::set<udp::endpoint> subscribers_;
};
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: server <port>\n";
return 1;
}
asio::io_context io_context;
using namespace std; // For atoi.
server s(io_context, atoi(argv[1]));
io_context.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << std::endl;
}
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/porthopper/client.cpp | //
// client.cpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio.hpp>
#include <algorithm>
#include <cstdlib>
#include <exception>
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include "protocol.hpp"
using asio::ip::tcp;
using asio::ip::udp;
int main(int argc, char* argv[])
{
try
{
if (argc != 3)
{
std::cerr << "Usage: client <host> <port>\n";
return 1;
}
using namespace std; // For atoi.
std::string host_name = argv[1];
std::string port = argv[2];
asio::io_context io_context;
// Determine the location of the server.
tcp::resolver resolver(io_context);
tcp::endpoint remote_endpoint = *resolver.resolve(host_name, port).begin();
// Establish the control connection to the server.
tcp::socket control_socket(io_context);
control_socket.connect(remote_endpoint);
// Create a datagram socket to receive data from the server.
udp::socket data_socket(io_context, udp::endpoint(udp::v4(), 0));
// Determine what port we will receive data on.
udp::endpoint data_endpoint = data_socket.local_endpoint();
// Ask the server to start sending us data.
control_request start = control_request::start(data_endpoint.port());
asio::write(control_socket, start.to_buffers());
unsigned long last_frame_number = 0;
for (;;)
{
// Receive 50 messages on the current data socket.
for (int i = 0; i < 50; ++i)
{
// Receive a frame from the server.
frame f;
data_socket.receive(f.to_buffers(), 0);
if (f.number() > last_frame_number)
{
last_frame_number = f.number();
std::cout << "\n" << f.payload();
}
}
// Time to switch to a new socket. To ensure seamless handover we will
// continue to receive packets using the old socket until data arrives on
// the new one.
std::cout << " Starting renegotiation";
// Create the new data socket.
udp::socket new_data_socket(io_context, udp::endpoint(udp::v4(), 0));
// Determine the new port we will use to receive data.
udp::endpoint new_data_endpoint = new_data_socket.local_endpoint();
// Ask the server to switch over to the new port.
control_request change = control_request::change(
data_endpoint.port(), new_data_endpoint.port());
std::error_code control_result;
asio::async_write(control_socket, change.to_buffers(),
[&](std::error_code ec, std::size_t /*length*/)
{
control_result = ec;
});
// Try to receive a frame from the server on the new data socket. If we
// successfully receive a frame on this new data socket we can consider
// the renegotation complete. In that case we will close the old data
// socket, which will cause any outstanding receive operation on it to be
// cancelled.
frame f1;
std::error_code new_data_socket_result;
new_data_socket.async_receive(f1.to_buffers(),
[&](std::error_code ec, std::size_t /*length*/)
{
new_data_socket_result = ec;
if (!ec)
{
// We have successfully received a frame on the new data socket,
// so we can close the old data socket. This will cancel any
// outstanding receive operation on the old data socket.
data_socket.close();
}
});
// This loop will continue until we have successfully completed the
// renegotiation (i.e. received a frame on the new data socket), or some
// unrecoverable error occurs.
bool done = false;
while (!done)
{
// Even though we're performing a renegotation, we want to continue
// receiving data as smoothly as possible. Therefore we will continue to
// try to receive a frame from the server on the old data socket. If we
// receive a frame on this socket we will interrupt the io_context,
// print the frame, and resume waiting for the other operations to
// complete.
frame f2;
done = true; // Let's be optimistic.
if (data_socket.is_open()) // May have been closed by receive handler.
{
data_socket.async_receive(f2.to_buffers(), 0,
[&](std::error_code ec, std::size_t /*length*/)
{
if (!ec)
{
// We have successfully received a frame on the old data
// socket. Stop the io_context so that we can print it.
io_context.stop();
done = false;
}
});
}
// Run the operations in parallel. This will block until all operations
// have finished, or until the io_context is interrupted. (No threads!)
io_context.restart();
io_context.run();
// If the io_context.run() was interrupted then we have received a frame
// on the old data socket. We need to keep waiting for the renegotation
// operations to complete.
if (!done)
{
if (f2.number() > last_frame_number)
{
last_frame_number = f2.number();
std::cout << "\n" << f2.payload();
}
}
}
// Since the loop has finished, we have either successfully completed
// the renegotation, or an error has occurred. First we'll check for
// errors.
if (control_result)
throw std::system_error(control_result);
if (new_data_socket_result)
throw std::system_error(new_data_socket_result);
// If we get here it means we have successfully started receiving data on
// the new data socket. This new data socket will be used from now on
// (until the next time we renegotiate).
std::cout << " Renegotiation complete";
data_socket = std::move(new_data_socket);
data_endpoint = new_data_endpoint;
if (f1.number() > last_frame_number)
{
last_frame_number = f1.number();
std::cout << "\n" << f1.payload();
}
}
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << std::endl;
}
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/socks4/sync_client.cpp | //
// sync_client.cpp
// ~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <array>
#include <iostream>
#include <iomanip>
#include <ostream>
#include <string>
#include <asio.hpp>
#include "socks4.hpp"
using asio::ip::tcp;
int main(int argc, char* argv[])
{
try
{
if (argc != 4)
{
std::cout << "Usage: sync_client <socks4server> <socks4port> <user>\n";
std::cout << "Examples:\n";
std::cout << " sync_client 127.0.0.1 1080 chris\n";
std::cout << " sync_client localhost socks chris\n";
return 1;
}
asio::io_context io_context;
// Get a list of endpoints corresponding to the SOCKS 4 server name.
tcp::resolver resolver(io_context);
auto endpoints = resolver.resolve(argv[1], argv[2]);
// Try each endpoint until we successfully establish a connection to the
// SOCKS 4 server.
tcp::socket socket(io_context);
asio::connect(socket, endpoints);
// Get an endpoint for the Boost website. This will be passed to the SOCKS
// 4 server. Explicitly specify IPv4 since SOCKS 4 does not support IPv6.
auto http_endpoint =
*resolver.resolve(tcp::v4(), "www.boost.org", "http").begin();
// Send the request to the SOCKS 4 server.
socks4::request socks_request(
socks4::request::connect, http_endpoint, argv[3]);
asio::write(socket, socks_request.buffers());
// Receive a response from the SOCKS 4 server.
socks4::reply socks_reply;
asio::read(socket, socks_reply.buffers());
// Check whether we successfully negotiated with the SOCKS 4 server.
if (!socks_reply.success())
{
std::cout << "Connection failed.\n";
std::cout << "status = 0x" << std::hex << socks_reply.status();
return 1;
}
// Form the HTTP request. We specify the "Connection: close" header so that
// the server will close the socket after transmitting the response. This
// will allow us to treat all data up until the EOF as the response.
std::string request =
"GET / HTTP/1.0\r\n"
"Host: www.boost.org\r\n"
"Accept: */*\r\n"
"Connection: close\r\n\r\n";
// Send the HTTP request.
asio::write(socket, asio::buffer(request));
// Read until EOF, writing data to output as we go.
std::array<char, 512> response;
std::error_code error;
while (std::size_t s = socket.read_some(
asio::buffer(response), error))
std::cout.write(response.data(), s);
if (error != asio::error::eof)
throw std::system_error(error);
}
catch (std::exception& e)
{
std::cout << "Exception: " << e.what() << "\n";
}
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/socks4/socks4.hpp | //
// socks4.hpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2024 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)
//
#ifndef SOCKS4_HPP
#define SOCKS4_HPP
#include <array>
#include <string>
#include <asio/buffer.hpp>
#include <asio/ip/tcp.hpp>
namespace socks4 {
const unsigned char version = 0x04;
class request
{
public:
enum command_type
{
connect = 0x01,
bind = 0x02
};
request(command_type cmd, const asio::ip::tcp::endpoint& endpoint,
const std::string& user_id)
: version_(version),
command_(cmd),
user_id_(user_id),
null_byte_(0)
{
// Only IPv4 is supported by the SOCKS 4 protocol.
if (endpoint.protocol() != asio::ip::tcp::v4())
{
throw std::system_error(
asio::error::address_family_not_supported);
}
// Convert port number to network byte order.
unsigned short port = endpoint.port();
port_high_byte_ = (port >> 8) & 0xff;
port_low_byte_ = port & 0xff;
// Save IP address in network byte order.
address_ = endpoint.address().to_v4().to_bytes();
}
std::array<asio::const_buffer, 7> buffers() const
{
return
{
{
asio::buffer(&version_, 1),
asio::buffer(&command_, 1),
asio::buffer(&port_high_byte_, 1),
asio::buffer(&port_low_byte_, 1),
asio::buffer(address_),
asio::buffer(user_id_),
asio::buffer(&null_byte_, 1)
}
};
}
private:
unsigned char version_;
unsigned char command_;
unsigned char port_high_byte_;
unsigned char port_low_byte_;
asio::ip::address_v4::bytes_type address_;
std::string user_id_;
unsigned char null_byte_;
};
class reply
{
public:
enum status_type
{
request_granted = 0x5a,
request_failed = 0x5b,
request_failed_no_identd = 0x5c,
request_failed_bad_user_id = 0x5d
};
reply()
: null_byte_(0),
status_()
{
}
std::array<asio::mutable_buffer, 5> buffers()
{
return
{
{
asio::buffer(&null_byte_, 1),
asio::buffer(&status_, 1),
asio::buffer(&port_high_byte_, 1),
asio::buffer(&port_low_byte_, 1),
asio::buffer(address_)
}
};
}
bool success() const
{
return null_byte_ == 0 && status_ == request_granted;
}
unsigned char status() const
{
return status_;
}
asio::ip::tcp::endpoint endpoint() const
{
unsigned short port = port_high_byte_;
port = (port << 8) & 0xff00;
port = port | port_low_byte_;
asio::ip::address_v4 address(address_);
return asio::ip::tcp::endpoint(address, port);
}
private:
unsigned char null_byte_;
unsigned char status_;
unsigned char port_high_byte_;
unsigned char port_low_byte_;
asio::ip::address_v4::bytes_type address_;
};
} // namespace socks4
#endif // SOCKS4_HPP
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/serialization/connection.hpp | //
// connection.hpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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)
//
#ifndef SERIALIZATION_CONNECTION_HPP
#define SERIALIZATION_CONNECTION_HPP
#include <asio.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <functional>
#include <iomanip>
#include <memory>
#include <string>
#include <sstream>
#include <tuple>
#include <vector>
namespace s11n_example {
/// The connection class provides serialization primitives on top of a socket.
/**
* Each message sent using this class consists of:
* @li An 8-byte header containing the length of the serialized data in
* hexadecimal.
* @li The serialized data.
*/
class connection
{
public:
/// Constructor.
connection(const asio::any_io_executor& ex)
: socket_(ex)
{
}
/// Get the underlying socket. Used for making a connection or for accepting
/// an incoming connection.
asio::ip::tcp::socket& socket()
{
return socket_;
}
/// Asynchronously write a data structure to the socket.
template <typename T, typename Handler>
void async_write(const T& t, Handler handler)
{
// Serialize the data first so we know how large it is.
std::ostringstream archive_stream;
boost::archive::text_oarchive archive(archive_stream);
archive << t;
outbound_data_ = archive_stream.str();
// Format the header.
std::ostringstream header_stream;
header_stream << std::setw(header_length)
<< std::hex << outbound_data_.size();
if (!header_stream || header_stream.str().size() != header_length)
{
// Something went wrong, inform the caller.
std::error_code error(asio::error::invalid_argument);
asio::post(socket_.get_executor(), std::bind(handler, error));
return;
}
outbound_header_ = header_stream.str();
// Write the serialized data to the socket. We use "gather-write" to send
// both the header and the data in a single write operation.
std::vector<asio::const_buffer> buffers;
buffers.push_back(asio::buffer(outbound_header_));
buffers.push_back(asio::buffer(outbound_data_));
asio::async_write(socket_, buffers, handler);
}
/// Asynchronously read a data structure from the socket.
template <typename T, typename Handler>
void async_read(T& t, Handler handler)
{
// Issue a read operation to read exactly the number of bytes in a header.
void (connection::*f)(const std::error_code&, T&, std::tuple<Handler>)
= &connection::handle_read_header<T, Handler>;
asio::async_read(socket_, asio::buffer(inbound_header_),
std::bind(f,
this, asio::placeholders::error, std::ref(t),
std::make_tuple(handler)));
}
/// Handle a completed read of a message header.
template <typename T, typename Handler>
void handle_read_header(const std::error_code& e,
T& t, std::tuple<Handler> handler)
{
if (e)
{
std::get<0>(handler)(e);
}
else
{
// Determine the length of the serialized data.
std::istringstream is(std::string(inbound_header_, header_length));
std::size_t inbound_data_size = 0;
if (!(is >> std::hex >> inbound_data_size))
{
// Header doesn't seem to be valid. Inform the caller.
std::error_code error(asio::error::invalid_argument);
std::get<0>(handler)(error);
return;
}
// Start an asynchronous call to receive the data.
inbound_data_.resize(inbound_data_size);
void (connection::*f)(
const std::error_code&,
T&, std::tuple<Handler>)
= &connection::handle_read_data<T, Handler>;
asio::async_read(socket_, asio::buffer(inbound_data_),
std::bind(f, this,
asio::placeholders::error, std::ref(t), handler));
}
}
/// Handle a completed read of message data.
template <typename T, typename Handler>
void handle_read_data(const std::error_code& e,
T& t, std::tuple<Handler> handler)
{
if (e)
{
std::get<0>(handler)(e);
}
else
{
// Extract the data structure from the data just received.
try
{
std::string archive_data(&inbound_data_[0], inbound_data_.size());
std::istringstream archive_stream(archive_data);
boost::archive::text_iarchive archive(archive_stream);
archive >> t;
}
catch (std::exception& e)
{
// Unable to decode data.
std::error_code error(asio::error::invalid_argument);
std::get<0>(handler)(error);
return;
}
// Inform caller that data has been received ok.
std::get<0>(handler)(e);
}
}
private:
/// The underlying socket.
asio::ip::tcp::socket socket_;
/// The size of a fixed length header.
enum { header_length = 8 };
/// Holds an outbound header.
std::string outbound_header_;
/// Holds the outbound data.
std::string outbound_data_;
/// Holds an inbound header.
char inbound_header_[header_length];
/// Holds the inbound data.
std::vector<char> inbound_data_;
};
typedef std::shared_ptr<connection> connection_ptr;
} // namespace s11n_example
#endif // SERIALIZATION_CONNECTION_HPP
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/serialization/server.cpp | //
// server.cpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio.hpp>
#include <functional>
#include <iostream>
#include <vector>
#include "connection.hpp" // Must come before boost/serialization headers.
#include <boost/serialization/vector.hpp>
#include "stock.hpp"
namespace s11n_example {
/// Serves stock quote information to any client that connects to it.
class server
{
public:
/// Constructor opens the acceptor and starts waiting for the first incoming
/// connection.
server(asio::io_context& io_context, unsigned short port)
: acceptor_(io_context,
asio::ip::tcp::endpoint(asio::ip::tcp::v4(), port))
{
// Create the data to be sent to each client.
stock s;
s.code = "ABC";
s.name = "A Big Company";
s.open_price = 4.56;
s.high_price = 5.12;
s.low_price = 4.33;
s.last_price = 4.98;
s.buy_price = 4.96;
s.buy_quantity = 1000;
s.sell_price = 4.99;
s.sell_quantity = 2000;
stocks_.push_back(s);
s.code = "DEF";
s.name = "Developer Entertainment Firm";
s.open_price = 20.24;
s.high_price = 22.88;
s.low_price = 19.50;
s.last_price = 19.76;
s.buy_price = 19.72;
s.buy_quantity = 34000;
s.sell_price = 19.85;
s.sell_quantity = 45000;
stocks_.push_back(s);
// Start an accept operation for a new connection.
connection_ptr new_conn(new connection(acceptor_.get_executor()));
acceptor_.async_accept(new_conn->socket(),
std::bind(&server::handle_accept, this,
asio::placeholders::error, new_conn));
}
/// Handle completion of a accept operation.
void handle_accept(const std::error_code& e, connection_ptr conn)
{
if (!e)
{
// Successfully accepted a new connection. Send the list of stocks to the
// client. The connection::async_write() function will automatically
// serialize the data structure for us.
conn->async_write(stocks_,
std::bind(&server::handle_write, this,
asio::placeholders::error, conn));
}
// Start an accept operation for a new connection.
connection_ptr new_conn(new connection(acceptor_.get_executor()));
acceptor_.async_accept(new_conn->socket(),
std::bind(&server::handle_accept, this,
asio::placeholders::error, new_conn));
}
/// Handle completion of a write operation.
void handle_write(const std::error_code& e, connection_ptr conn)
{
// Nothing to do. The socket will be closed automatically when the last
// reference to the connection object goes away.
}
private:
/// The acceptor object used to accept incoming socket connections.
asio::ip::tcp::acceptor acceptor_;
/// The data to be sent to each client.
std::vector<stock> stocks_;
};
} // namespace s11n_example
int main(int argc, char* argv[])
{
try
{
// Check command line arguments.
if (argc != 2)
{
std::cerr << "Usage: server <port>" << std::endl;
return 1;
}
unsigned short port = std::stoi(argv[1]);
asio::io_context io_context;
s11n_example::server server(io_context, port);
io_context.run();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/serialization/stock.hpp | //
// stock.hpp
// ~~~~~~~~~
//
// Copyright (c) 2003-2024 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)
//
#ifndef SERIALIZATION_STOCK_HPP
#define SERIALIZATION_STOCK_HPP
#include <string>
namespace s11n_example {
/// Structure to hold information about a single stock.
struct stock
{
std::string code;
std::string name;
double open_price;
double high_price;
double low_price;
double last_price;
double buy_price;
int buy_quantity;
double sell_price;
int sell_quantity;
template <typename Archive>
void serialize(Archive& ar, const unsigned int version)
{
ar & code;
ar & name;
ar & open_price;
ar & high_price;
ar & low_price;
ar & last_price;
ar & buy_price;
ar & buy_quantity;
ar & sell_price;
ar & sell_quantity;
}
};
} // namespace s11n_example
#endif // SERIALIZATION_STOCK_HPP
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/serialization/client.cpp | //
// client.cpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio.hpp>
#include <functional>
#include <iostream>
#include <vector>
#include "connection.hpp" // Must come before boost/serialization headers.
#include <boost/serialization/vector.hpp>
#include "stock.hpp"
namespace s11n_example {
/// Downloads stock quote information from a server.
class client
{
public:
/// Constructor starts the asynchronous connect operation.
client(asio::io_context& io_context,
const std::string& host, const std::string& service)
: connection_(io_context.get_executor())
{
// Resolve the host name into an IP address.
asio::ip::tcp::resolver resolver(io_context);
asio::ip::tcp::resolver::query query(host, service);
asio::ip::tcp::resolver::iterator endpoint_iterator =
resolver.resolve(query);
// Start an asynchronous connect operation.
asio::async_connect(connection_.socket(), endpoint_iterator,
std::bind(&client::handle_connect, this,
asio::placeholders::error));
}
/// Handle completion of a connect operation.
void handle_connect(const asio::error_code& e)
{
if (!e)
{
// Successfully established connection. Start operation to read the list
// of stocks. The connection::async_read() function will automatically
// decode the data that is read from the underlying socket.
connection_.async_read(stocks_,
std::bind(&client::handle_read, this,
asio::placeholders::error));
}
else
{
// An error occurred. Log it and return. Since we are not starting a new
// operation the io_context will run out of work to do and the client will
// exit.
std::cerr << e.message() << std::endl;
}
}
/// Handle completion of a read operation.
void handle_read(const asio::error_code& e)
{
if (!e)
{
// Print out the data that was received.
for (std::size_t i = 0; i < stocks_.size(); ++i)
{
std::cout << "Stock number " << i << "\n";
std::cout << " code: " << stocks_[i].code << "\n";
std::cout << " name: " << stocks_[i].name << "\n";
std::cout << " open_price: " << stocks_[i].open_price << "\n";
std::cout << " high_price: " << stocks_[i].high_price << "\n";
std::cout << " low_price: " << stocks_[i].low_price << "\n";
std::cout << " last_price: " << stocks_[i].last_price << "\n";
std::cout << " buy_price: " << stocks_[i].buy_price << "\n";
std::cout << " buy_quantity: " << stocks_[i].buy_quantity << "\n";
std::cout << " sell_price: " << stocks_[i].sell_price << "\n";
std::cout << " sell_quantity: " << stocks_[i].sell_quantity << "\n";
}
}
else
{
// An error occurred.
std::cerr << e.message() << std::endl;
}
// Since we are not starting a new operation the io_context will run out of
// work to do and the client will exit.
}
private:
/// The connection to the server.
connection connection_;
/// The data received from the server.
std::vector<stock> stocks_;
};
} // namespace s11n_example
int main(int argc, char* argv[])
{
try
{
// Check command line arguments.
if (argc != 3)
{
std::cerr << "Usage: client <host> <port>" << std::endl;
return 1;
}
asio::io_context io_context;
s11n_example::client client(io_context, argv[1], argv[2]);
io_context.run();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/spawn/parallel_grep.cpp | //
// parallel_grep.cpp
// ~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio/detached.hpp>
#include <asio/dispatch.hpp>
#include <asio/post.hpp>
#include <asio/spawn.hpp>
#include <asio/strand.hpp>
#include <asio/thread_pool.hpp>
#include <fstream>
#include <iostream>
#include <string>
using asio::detached;
using asio::dispatch;
using asio::spawn;
using asio::strand;
using asio::thread_pool;
using asio::yield_context;
int main(int argc, char* argv[])
{
try
{
if (argc < 2)
{
std::cerr << "Usage: parallel_grep <string> <files...>\n";
return 1;
}
// We use a fixed size pool of threads for reading the input files. The
// number of threads is automatically determined based on the number of
// CPUs available in the system.
thread_pool pool;
// To prevent the output from being garbled, we use a strand to synchronise
// printing.
strand<thread_pool::executor_type> output_strand(pool.get_executor());
// Spawn a new coroutine for each file specified on the command line.
std::string search_string = argv[1];
for (int argn = 2; argn < argc; ++argn)
{
std::string input_file = argv[argn];
spawn(pool,
[=](yield_context yield)
{
std::ifstream is(input_file.c_str());
std::string line;
std::size_t line_num = 0;
while (std::getline(is, line))
{
// If we find a match, send a message to the output.
if (line.find(search_string) != std::string::npos)
{
dispatch(output_strand,
[=]
{
std::cout << input_file << ':' << line << std::endl;
});
}
// Every so often we yield control to another coroutine.
if (++line_num % 10 == 0)
post(yield);
}
}, detached);
}
// Join the thread pool to wait for all the spawned tasks to complete.
pool.join();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/spawn/echo_server.cpp | //
// echo_server.cpp
// ~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio/detached.hpp>
#include <asio/io_context.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/spawn.hpp>
#include <asio/steady_timer.hpp>
#include <asio/write.hpp>
#include <iostream>
#include <memory>
using asio::ip::tcp;
class session : public std::enable_shared_from_this<session>
{
public:
explicit session(asio::io_context& io_context, tcp::socket socket)
: socket_(std::move(socket)),
timer_(io_context),
strand_(io_context.get_executor())
{
}
void go()
{
auto self(shared_from_this());
asio::spawn(strand_,
[this, self](asio::yield_context yield)
{
try
{
char data[128];
for (;;)
{
timer_.expires_after(std::chrono::seconds(10));
std::size_t n = socket_.async_read_some(asio::buffer(data), yield);
asio::async_write(socket_, asio::buffer(data, n), yield);
}
}
catch (std::exception& e)
{
socket_.close();
timer_.cancel();
}
}, asio::detached);
asio::spawn(strand_,
[this, self](asio::yield_context yield)
{
while (socket_.is_open())
{
std::error_code ignored_ec;
timer_.async_wait(yield[ignored_ec]);
if (timer_.expiry() <= asio::steady_timer::clock_type::now())
socket_.close();
}
}, asio::detached);
}
private:
tcp::socket socket_;
asio::steady_timer timer_;
asio::strand<asio::io_context::executor_type> strand_;
};
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: echo_server <port>\n";
return 1;
}
asio::io_context io_context;
asio::spawn(io_context,
[&](asio::yield_context yield)
{
tcp::acceptor acceptor(io_context,
tcp::endpoint(tcp::v4(), std::atoi(argv[1])));
for (;;)
{
std::error_code ec;
tcp::socket socket(io_context);
acceptor.async_accept(socket, yield[ec]);
if (!ec)
{
std::make_shared<session>(io_context, std::move(socket))->go();
}
}
},
[](std::exception_ptr e)
{
if (e)
std::rethrow_exception(e);
});
io_context.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/local/fd_passing_stream_client.cpp | //
// fd_passing_stream_client.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
// Copyright (c) 2021 Heiko Hund (heiko at openvpn dot net)
//
// 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)
//
// Demonstrates how to pass file descriptors between processes with Asio.
// The client send a file name (destfile) to the server. The server opens
// the file and the associated file descriptor back to the client.
#include <cstdlib>
#include <cstring>
#include <iostream>
#include "asio.hpp"
#if defined(ASIO_HAS_LOCAL_SOCKETS)
#include <sys/types.h>
#include <sys/socket.h>
using asio::local::stream_protocol;
constexpr std::size_t max_length = 1024;
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: fd_passing_stream_client <serversocket>\n";
return 1;
}
asio::io_context io_context;
stream_protocol::socket s(io_context);
s.connect(stream_protocol::endpoint(argv[1]));
std::cout << "Enter path to write to: ";
char request[max_length];
std::cin.getline(request, max_length);
size_t request_length = std::strlen(request);
asio::write(s, asio::buffer(request, request_length));
char reply[max_length];
struct msghdr msg = {};
struct iovec iov = { reply, sizeof(reply) };
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
union
{
struct cmsghdr align;
char buf[CMSG_SPACE(sizeof(int))];
} cmsgu;
msg.msg_control = cmsgu.buf;
msg.msg_controllen = sizeof(cmsgu.buf);
::recvmsg(s.native_handle(), &msg, 0);
int fd = -1;
struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
while (cmsg != NULL)
{
if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
{
std::memcpy(&fd, CMSG_DATA(cmsg), sizeof(fd));
break;
}
cmsg = CMSG_NXTHDR(&msg, cmsg);
}
if (fd != -1)
{
std::cout << "File descriptor received is: " << fd << "\n";
FILE* f(::fdopen(fd, "w+"));
if (f)
{
::fprintf(f, "stream_client writing to received fd #%d\n", fd);
::fclose(f);
}
else
::close(fd);
}
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
#else // defined(ASIO_HAS_LOCAL_SOCKETS)
# error Local sockets not available on this platform.
#endif // defined(ASIO_HAS_LOCAL_SOCKETS)
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/local/stream_server.cpp | //
// stream_server.cpp
// ~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <array>
#include <cstdio>
#include <iostream>
#include <memory>
#include "asio.hpp"
#if defined(ASIO_HAS_LOCAL_SOCKETS)
using asio::local::stream_protocol;
class session
: public std::enable_shared_from_this<session>
{
public:
session(stream_protocol::socket sock)
: socket_(std::move(sock))
{
}
void start()
{
do_read();
}
private:
void do_read()
{
auto self(shared_from_this());
socket_.async_read_some(asio::buffer(data_),
[this, self](std::error_code ec, std::size_t length)
{
if (!ec)
do_write(length);
});
}
void do_write(std::size_t length)
{
auto self(shared_from_this());
asio::async_write(socket_,
asio::buffer(data_, length),
[this, self](std::error_code ec, std::size_t /*length*/)
{
if (!ec)
do_read();
});
}
// The socket used to communicate with the client.
stream_protocol::socket socket_;
// Buffer used to store data received from the client.
std::array<char, 1024> data_;
};
class server
{
public:
server(asio::io_context& io_context, const std::string& file)
: acceptor_(io_context, stream_protocol::endpoint(file))
{
do_accept();
}
private:
void do_accept()
{
acceptor_.async_accept(
[this](std::error_code ec, stream_protocol::socket socket)
{
if (!ec)
{
std::make_shared<session>(std::move(socket))->start();
}
do_accept();
});
}
stream_protocol::acceptor acceptor_;
};
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: stream_server <file>\n";
std::cerr << "*** WARNING: existing file is removed ***\n";
return 1;
}
asio::io_context io_context;
std::remove(argv[1]);
server s(io_context, argv[1]);
io_context.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
#else // defined(ASIO_HAS_LOCAL_SOCKETS)
# error Local sockets not available on this platform.
#endif // defined(ASIO_HAS_LOCAL_SOCKETS)
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/local/iostream_client.cpp | //
// stream_client.cpp
// ~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <cstring>
#include <iostream>
#include "asio.hpp"
#if defined(ASIO_HAS_LOCAL_SOCKETS)
using asio::local::stream_protocol;
constexpr std::size_t max_length = 1024;
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: iostream_client <file>\n";
return 1;
}
stream_protocol::endpoint ep(argv[1]);
stream_protocol::iostream s(ep);
if (!s)
{
std::cerr << "Unable to connect: " << s.error().message() << std::endl;
return 1;
}
std::cout << "Enter message: ";
char request[max_length];
std::cin.getline(request, max_length);
size_t length = std::strlen(request);
s << request;
char reply[max_length];
s.read(reply, length);
std::cout << "Reply is: ";
std::cout.write(reply, length);
std::cout << "\n";
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
#else // defined(ASIO_HAS_LOCAL_SOCKETS)
# error Local sockets not available on this platform.
#endif // defined(ASIO_HAS_LOCAL_SOCKETS)
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/local/stream_client.cpp | //
// stream_client.cpp
// ~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <cstdlib>
#include <cstring>
#include <iostream>
#include "asio.hpp"
#if defined(ASIO_HAS_LOCAL_SOCKETS)
using asio::local::stream_protocol;
constexpr std::size_t max_length = 1024;
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: stream_client <file>\n";
return 1;
}
asio::io_context io_context;
stream_protocol::socket s(io_context);
s.connect(stream_protocol::endpoint(argv[1]));
std::cout << "Enter message: ";
char request[max_length];
std::cin.getline(request, max_length);
size_t request_length = std::strlen(request);
asio::write(s, asio::buffer(request, request_length));
char reply[max_length];
size_t reply_length = asio::read(s,
asio::buffer(reply, request_length));
std::cout << "Reply is: ";
std::cout.write(reply, reply_length);
std::cout << "\n";
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
#else // defined(ASIO_HAS_LOCAL_SOCKETS)
# error Local sockets not available on this platform.
#endif // defined(ASIO_HAS_LOCAL_SOCKETS)
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/local/fd_passing_stream_server.cpp | //
// fd_passing_stream_server.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
// Copyright (c) 2021 Heiko Hund (heiko at openvpn dot net)
//
// 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)
//
// Demonstrates how to pass file descriptors between processes with Asio.
// The client sends a file name to the server. The server opens the file and
// passes the associated file descriptor back to the client.
#include <array>
#include <cstdio>
#include <cassert>
#include <iostream>
#include <memory>
#include "asio.hpp"
#if defined(ASIO_HAS_LOCAL_SOCKETS)
using asio::local::stream_protocol;
class session
: public std::enable_shared_from_this<session>
{
public:
session(stream_protocol::socket sock)
: socket_(std::move(sock))
{
}
void start()
{
do_read();
}
private:
void do_read()
{
auto self(shared_from_this());
socket_.async_read_some(asio::buffer(data_),
[this, self](std::error_code ec, std::size_t length)
{
if (ec)
return;
assert(length < data_.size());
data_[length] = 0;
do_write(data_.data());
});
}
void do_write(const char* filename)
{
auto self(shared_from_this());
socket_.async_wait(stream_protocol::socket::wait_write,
[this, self, filename](std::error_code ec)
{
if (ec)
return;
FILE* f(::fopen(filename, "w+"));
if (!f)
return;
struct msghdr msg = {};
char buf[] = { 0 };
struct iovec iov = { buf, sizeof(buf) };
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
union
{
struct cmsghdr align;
char buf[CMSG_SPACE(sizeof(int))];
} cmsgu;
msg.msg_control = cmsgu.buf;
msg.msg_controllen = sizeof(cmsgu.buf);
struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_len = CMSG_LEN(sizeof(int));
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
int fd = ::fileno(f);
std::memcpy(CMSG_DATA(cmsg), &fd, sizeof(int));
ssize_t s(::sendmsg(socket_.native_handle(), &msg, 0));
::fclose(f);
if (s != -1)
do_read();
});
}
// The socket used to communicate with the client.
stream_protocol::socket socket_;
// Buffer used to store data received from the client.
std::array<char, 1024> data_;
};
class server
{
public:
server(asio::io_context& io_context, const std::string& file)
: acceptor_(io_context, stream_protocol::endpoint(file))
{
do_accept();
}
private:
void do_accept()
{
acceptor_.async_accept(
[this](std::error_code ec, stream_protocol::socket socket)
{
if (!ec)
{
std::make_shared<session>(std::move(socket))->start();
}
do_accept();
});
}
stream_protocol::acceptor acceptor_;
};
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: fd_passing_stream_server <socketfile>\n";
std::cerr << "*** WARNING: existing file is removed ***\n";
return 1;
}
asio::io_context io_context;
std::remove(argv[1]);
server s(io_context, argv[1]);
io_context.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
#else // defined(ASIO_HAS_LOCAL_SOCKETS)
# error Local sockets not available on this platform.
#endif // defined(ASIO_HAS_LOCAL_SOCKETS)
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/local/connect_pair.cpp | //
// connect_pair.cpp
// ~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <array>
#include <iostream>
#include <string>
#include <cctype>
#include <asio.hpp>
#if defined(ASIO_HAS_LOCAL_SOCKETS)
using asio::local::stream_protocol;
class uppercase_filter
{
public:
uppercase_filter(stream_protocol::socket sock)
: socket_(std::move(sock))
{
read();
}
private:
void read()
{
socket_.async_read_some(asio::buffer(data_),
[this](std::error_code ec, std::size_t size)
{
if (!ec)
{
// Compute result.
for (std::size_t i = 0; i < size; ++i)
data_[i] = std::toupper(data_[i]);
// Send result.
write(size);
}
else
{
throw std::system_error(ec);
}
});
}
void write(std::size_t size)
{
asio::async_write(socket_, asio::buffer(data_, size),
[this](std::error_code ec, std::size_t /*size*/)
{
if (!ec)
{
// Wait for request.
read();
}
else
{
throw std::system_error(ec);
}
});
}
stream_protocol::socket socket_;
std::array<char, 512> data_;
};
int main()
{
try
{
asio::io_context io_context;
// Create a connected pair and pass one end to a filter.
stream_protocol::socket socket(io_context);
stream_protocol::socket filter_socket(io_context);
asio::local::connect_pair(socket, filter_socket);
uppercase_filter filter(std::move(filter_socket));
// The io_context runs in a background thread to perform filtering.
asio::thread thread(
[&io_context]()
{
try
{
io_context.run();
}
catch (std::exception& e)
{
std::cerr << "Exception in thread: " << e.what() << "\n";
std::exit(1);
}
});
for (;;)
{
// Collect request from user.
std::cout << "Enter a string: ";
std::string request;
std::getline(std::cin, request);
// Send request to filter.
asio::write(socket, asio::buffer(request));
// Wait for reply from filter.
std::vector<char> reply(request.size());
asio::read(socket, asio::buffer(reply));
// Show reply to user.
std::cout << "Result: ";
std::cout.write(&reply[0], request.size());
std::cout << std::endl;
}
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
std::exit(1);
}
}
#else // defined(ASIO_HAS_LOCAL_SOCKETS)
# error Local sockets not available on this platform.
#endif // defined(ASIO_HAS_LOCAL_SOCKETS)
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/operations/composed_8.cpp | //
// composed_8.cpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio/compose.hpp>
#include <asio/deferred.hpp>
#include <asio/io_context.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/steady_timer.hpp>
#include <asio/use_future.hpp>
#include <asio/write.hpp>
#include <functional>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
using asio::ip::tcp;
// NOTE: This example requires the new asio::async_compose function. For
// an example that works with the Networking TS style of completion tokens,
// please see an older version of asio.
//------------------------------------------------------------------------------
// This composed operation shows composition of multiple underlying operations,
// using asio's stackless coroutines support to express the flow of control. It
// automatically serialises a message, using its I/O streams insertion
// operator, before sending it N times on the socket. To do this, it must
// allocate a buffer for the encoded message and ensure this buffer's validity
// until all underlying async_write operation complete. A one second delay is
// inserted prior to each write operation, using a steady_timer.
#include <asio/yield.hpp>
// In this example, the composed operation's logic is implemented as a state
// machine within a hand-crafted function object.
struct async_write_messages_implementation
{
// The implementation holds a reference to the socket as it is used for
// multiple async_write operations.
tcp::socket& socket_;
// The allocated buffer for the encoded message. The std::unique_ptr smart
// pointer is move-only, and as a consequence our implementation is also
// move-only.
std::unique_ptr<std::string> encoded_message_;
// The repeat count remaining.
std::size_t repeat_count_;
// A steady timer used for introducing a delay.
std::unique_ptr<asio::steady_timer> delay_timer_;
// The coroutine state.
asio::coroutine coro_;
// The first argument to our function object's call operator is a reference
// to the enclosing intermediate completion handler. This intermediate
// completion handler is provided for us by the asio::async_compose
// function, and takes care of all the details required to implement a
// conforming asynchronous operation. When calling an underlying asynchronous
// operation, we pass it this enclosing intermediate completion handler
// as the completion token.
//
// All arguments after the first must be defaulted to allow the state machine
// to be started, as well as to allow the completion handler to match the
// completion signature of both the async_write and steady_timer::async_wait
// operations.
template <typename Self>
void operator()(Self& self,
const std::error_code& error = std::error_code(),
std::size_t = 0)
{
reenter (coro_)
{
while (repeat_count_ > 0)
{
--repeat_count_;
delay_timer_->expires_after(std::chrono::seconds(1));
yield delay_timer_->async_wait(std::move(self));
if (error)
break;
yield asio::async_write(socket_,
asio::buffer(*encoded_message_), std::move(self));
if (error)
break;
}
// Deallocate the encoded message and delay timer before calling the
// user-supplied completion handler.
encoded_message_.reset();
delay_timer_.reset();
// Call the user-supplied handler with the result of the operation.
self.complete(error);
}
}
};
#include <asio/unyield.hpp>
template <typename T, typename CompletionToken>
auto async_write_messages(tcp::socket& socket,
const T& message, std::size_t repeat_count,
CompletionToken&& token)
// The return type of the initiating function is deduced from the combination
// of:
//
// - the CompletionToken type,
// - the completion handler signature, and
// - the asynchronous operation's initiation function object.
//
// When the completion token is a simple callback, the return type is always
// void. In this example, when the completion token is asio::yield_context
// (used for stackful coroutines) the return type would also be void, as
// there is no non-error argument to the completion handler. When the
// completion token is asio::use_future it would be std::future<void>. When
// the completion token is asio::deferred, the return type differs for each
// asynchronous operation.
//
// In C++11 we deduce the type from the call to asio::async_compose.
-> decltype(
asio::async_compose<
CompletionToken, void(std::error_code)>(
std::declval<async_write_messages_implementation>(),
token, socket))
{
// Encode the message and copy it into an allocated buffer. The buffer will
// be maintained for the lifetime of the composed asynchronous operation.
std::ostringstream os;
os << message;
std::unique_ptr<std::string> encoded_message(new std::string(os.str()));
// Create a steady_timer to be used for the delay between messages.
std::unique_ptr<asio::steady_timer> delay_timer(
new asio::steady_timer(socket.get_executor()));
// The asio::async_compose function takes:
//
// - our asynchronous operation implementation,
// - the completion token,
// - the completion handler signature, and
// - any I/O objects (or executors) used by the operation
//
// It then wraps our implementation in an intermediate completion handler
// that meets the requirements of a conforming asynchronous operation. This
// includes tracking outstanding work against the I/O executors associated
// with the operation (in this example, this is the socket's executor).
return asio::async_compose<
CompletionToken, void(std::error_code)>(
async_write_messages_implementation{socket,
std::move(encoded_message), repeat_count,
std::move(delay_timer), asio::coroutine()},
token, socket);
}
//------------------------------------------------------------------------------
void test_callback()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using a lambda as a callback.
async_write_messages(socket, "Testing callback\r\n", 5,
[](const std::error_code& error)
{
if (!error)
{
std::cout << "Messages sent\n";
}
else
{
std::cout << "Error: " << error.message() << "\n";
}
});
io_context.run();
}
//------------------------------------------------------------------------------
void test_deferred()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using the deferred completion token. This
// token causes the operation's initiating function to package up the
// operation and its arguments to return a function object, which may then be
// used to launch the asynchronous operation.
auto op = async_write_messages(socket,
"Testing deferred\r\n", 5, asio::deferred);
// Launch the operation using a lambda as a callback.
std::move(op)(
[](const std::error_code& error)
{
if (!error)
{
std::cout << "Messages sent\n";
}
else
{
std::cout << "Error: " << error.message() << "\n";
}
});
io_context.run();
}
//------------------------------------------------------------------------------
void test_future()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using the use_future completion token.
// This token causes the operation's initiating function to return a future,
// which may be used to synchronously wait for the result of the operation.
std::future<void> f = async_write_messages(
socket, "Testing future\r\n", 5, asio::use_future);
io_context.run();
try
{
// Get the result of the operation.
f.get();
std::cout << "Messages sent\n";
}
catch (const std::exception& e)
{
std::cout << "Error: " << e.what() << "\n";
}
}
//------------------------------------------------------------------------------
int main()
{
test_callback();
test_deferred();
test_future();
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/operations/composed_6.cpp | //
// composed_6.cpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio/deferred.hpp>
#include <asio/executor_work_guard.hpp>
#include <asio/io_context.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/steady_timer.hpp>
#include <asio/use_future.hpp>
#include <asio/write.hpp>
#include <functional>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
using asio::ip::tcp;
// NOTE: This example requires the new asio::async_initiate function. For
// an example that works with the Networking TS style of completion tokens,
// please see an older version of asio.
//------------------------------------------------------------------------------
// This composed operation shows composition of multiple underlying operations.
// It automatically serialises a message, using its I/O streams insertion
// operator, before sending it N times on the socket. To do this, it must
// allocate a buffer for the encoded message and ensure this buffer's validity
// until all underlying async_write operation complete. A one second delay is
// inserted prior to each write operation, using a steady_timer.
// In addition to determining the mechanism by which an asynchronous operation
// delivers its result, a completion token also determines the time when the
// operation commences. For example, when the completion token is a simple
// callback the operation commences before the initiating function returns.
// However, if the completion token's delivery mechanism uses a future, we
// might instead want to defer initiation of the operation until the returned
// future object is waited upon.
//
// To enable this, when implementing an asynchronous operation we must package
// the initiation step as a function object.
struct async_write_message_initiation
{
// The initiation function object's call operator is passed the concrete
// completion handler produced by the completion token. This completion
// handler matches the asynchronous operation's completion handler signature,
// which in this example is:
//
// void(std::error_code error)
//
// The initiation function object also receives any additional arguments
// required to start the operation. (Note: We could have instead passed these
// arguments as members in the initiaton function object. However, we should
// prefer to propagate them as function call arguments as this allows the
// completion token to optimise how they are passed. For example, a lazy
// future which defers initiation would need to make a decay-copy of the
// arguments, but when using a simple callback the arguments can be trivially
// forwarded straight through.)
template <typename CompletionHandler>
void operator()(CompletionHandler&& completion_handler, tcp::socket& socket,
std::unique_ptr<std::string> encoded_message, std::size_t repeat_count,
std::unique_ptr<asio::steady_timer> delay_timer) const
{
// In this example, the composed operation's intermediate completion
// handler is implemented as a hand-crafted function object.
struct intermediate_completion_handler
{
// The intermediate completion handler holds a reference to the socket as
// it is used for multiple async_write operations, as well as for
// obtaining the I/O executor (see get_executor below).
tcp::socket& socket_;
// The allocated buffer for the encoded message. The std::unique_ptr
// smart pointer is move-only, and as a consequence our intermediate
// completion handler is also move-only.
std::unique_ptr<std::string> encoded_message_;
// The repeat count remaining.
std::size_t repeat_count_;
// A steady timer used for introducing a delay.
std::unique_ptr<asio::steady_timer> delay_timer_;
// To manage the cycle between the multiple underlying asychronous
// operations, our intermediate completion handler is implemented as a
// state machine.
enum { starting, waiting, writing } state_;
// As our composed operation performs multiple underlying I/O operations,
// we should maintain a work object against the I/O executor. This tells
// the I/O executor that there is still more work to come in the future.
asio::executor_work_guard<tcp::socket::executor_type> io_work_;
// The user-supplied completion handler, called once only on completion
// of the entire composed operation.
typename std::decay<CompletionHandler>::type handler_;
// By having a default value for the second argument, this function call
// operator matches the completion signature of both the async_write and
// steady_timer::async_wait operations.
void operator()(const std::error_code& error, std::size_t = 0)
{
if (!error)
{
switch (state_)
{
case starting:
case writing:
if (repeat_count_ > 0)
{
--repeat_count_;
state_ = waiting;
delay_timer_->expires_after(std::chrono::seconds(1));
delay_timer_->async_wait(std::move(*this));
return; // Composed operation not yet complete.
}
break; // Composed operation complete, continue below.
case waiting:
state_ = writing;
asio::async_write(socket_,
asio::buffer(*encoded_message_), std::move(*this));
return; // Composed operation not yet complete.
}
}
// This point is reached only on completion of the entire composed
// operation.
// We no longer have any future work coming for the I/O executor.
io_work_.reset();
// Deallocate the encoded message and delay timer before calling the
// user-supplied completion handler.
encoded_message_.reset();
delay_timer_.reset();
// Call the user-supplied handler with the result of the operation.
handler_(error);
}
// It is essential to the correctness of our composed operation that we
// preserve the executor of the user-supplied completion handler. With a
// hand-crafted function object we can do this by defining a nested type
// executor_type and member function get_executor. These obtain the
// completion handler's associated executor, and default to the I/O
// executor - in this case the executor of the socket - if the completion
// handler does not have its own.
using executor_type = asio::associated_executor_t<
typename std::decay<CompletionHandler>::type,
tcp::socket::executor_type>;
executor_type get_executor() const noexcept
{
return asio::get_associated_executor(
handler_, socket_.get_executor());
}
// Although not necessary for correctness, we may also preserve the
// allocator of the user-supplied completion handler. This is achieved by
// defining a nested type allocator_type and member function
// get_allocator. These obtain the completion handler's associated
// allocator, and default to std::allocator<void> if the completion
// handler does not have its own.
using allocator_type = asio::associated_allocator_t<
typename std::decay<CompletionHandler>::type,
std::allocator<void>>;
allocator_type get_allocator() const noexcept
{
return asio::get_associated_allocator(
handler_, std::allocator<void>{});
}
};
// Initiate the underlying async_write operation using our intermediate
// completion handler.
auto encoded_message_buffer = asio::buffer(*encoded_message);
asio::async_write(socket, encoded_message_buffer,
intermediate_completion_handler{
socket, std::move(encoded_message),
repeat_count, std::move(delay_timer),
intermediate_completion_handler::starting,
asio::make_work_guard(socket.get_executor()),
std::forward<CompletionHandler>(completion_handler)});
}
};
template <typename T, typename CompletionToken>
auto async_write_messages(tcp::socket& socket,
const T& message, std::size_t repeat_count,
CompletionToken&& token)
// The return type of the initiating function is deduced from the combination
// of:
//
// - the CompletionToken type,
// - the completion handler signature, and
// - the asynchronous operation's initiation function object.
//
// When the completion token is a simple callback, the return type is always
// void. In this example, when the completion token is asio::yield_context
// (used for stackful coroutines) the return type would also be void, as
// there is no non-error argument to the completion handler. When the
// completion token is asio::use_future it would be std::future<void>. When
// the completion token is asio::deferred, the return type differs for each
// asynchronous operation.
//
// In C++11 we deduce the type from the call to asio::async_initiate.
-> decltype(
asio::async_initiate<
CompletionToken, void(std::error_code)>(
async_write_message_initiation(), token, std::ref(socket),
std::declval<std::unique_ptr<std::string>>(), repeat_count,
std::declval<std::unique_ptr<asio::steady_timer>>()))
{
// Encode the message and copy it into an allocated buffer. The buffer will
// be maintained for the lifetime of the composed asynchronous operation.
std::ostringstream os;
os << message;
std::unique_ptr<std::string> encoded_message(new std::string(os.str()));
// Create a steady_timer to be used for the delay between messages.
std::unique_ptr<asio::steady_timer> delay_timer(
new asio::steady_timer(socket.get_executor()));
// The asio::async_initiate function takes:
//
// - our initiation function object,
// - the completion token,
// - the completion handler signature, and
// - any additional arguments we need to initiate the operation.
//
// It then asks the completion token to create a completion handler (i.e. a
// callback) with the specified signature, and invoke the initiation function
// object with this completion handler as well as the additional arguments.
// The return value of async_initiate is the result of our operation's
// initiating function.
//
// Note that we wrap non-const reference arguments in std::reference_wrapper
// to prevent incorrect decay-copies of these objects.
return asio::async_initiate<
CompletionToken, void(std::error_code)>(
async_write_message_initiation(), token, std::ref(socket),
std::move(encoded_message), repeat_count, std::move(delay_timer));
}
//------------------------------------------------------------------------------
void test_callback()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using a lambda as a callback.
async_write_messages(socket, "Testing callback\r\n", 5,
[](const std::error_code& error)
{
if (!error)
{
std::cout << "Messages sent\n";
}
else
{
std::cout << "Error: " << error.message() << "\n";
}
});
io_context.run();
}
//------------------------------------------------------------------------------
void test_deferred()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using the deferred completion token. This
// token causes the operation's initiating function to package up the
// operation and its arguments to return a function object, which may then be
// used to launch the asynchronous operation.
auto op = async_write_messages(socket,
"Testing deferred\r\n", 5, asio::deferred);
// Launch the operation using a lambda as a callback.
std::move(op)(
[](const std::error_code& error)
{
if (!error)
{
std::cout << "Messages sent\n";
}
else
{
std::cout << "Error: " << error.message() << "\n";
}
});
io_context.run();
}
//------------------------------------------------------------------------------
void test_future()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using the use_future completion token.
// This token causes the operation's initiating function to return a future,
// which may be used to synchronously wait for the result of the operation.
std::future<void> f = async_write_messages(
socket, "Testing future\r\n", 5, asio::use_future);
io_context.run();
try
{
// Get the result of the operation.
f.get();
std::cout << "Messages sent\n";
}
catch (const std::exception& e)
{
std::cout << "Error: " << e.what() << "\n";
}
}
//------------------------------------------------------------------------------
int main()
{
test_callback();
test_deferred();
test_future();
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/operations/composed_2.cpp | //
// composed_2.cpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio/deferred.hpp>
#include <asio/io_context.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/use_future.hpp>
#include <asio/write.hpp>
#include <cstring>
#include <iostream>
#include <string>
#include <type_traits>
#include <utility>
using asio::ip::tcp;
// NOTE: This example requires the new asio::async_initiate function. For
// an example that works with the Networking TS style of completion tokens,
// please see an older version of asio.
//------------------------------------------------------------------------------
// This next simplest example of a composed asynchronous operation involves
// repackaging multiple operations but choosing to invoke just one of them. All
// of these underlying operations have the same completion signature. The
// asynchronous operation requirements are met by delegating responsibility to
// the underlying operations.
// In addition to determining the mechanism by which an asynchronous operation
// delivers its result, a completion token also determines the time when the
// operation commences. For example, when the completion token is a simple
// callback the operation commences before the initiating function returns.
// However, if the completion token's delivery mechanism uses a future, we
// might instead want to defer initiation of the operation until the returned
// future object is waited upon.
//
// To enable this, when implementing an asynchronous operation we must package
// the initiation step as a function object.
struct async_write_message_initiation
{
// The initiation function object's call operator is passed the concrete
// completion handler produced by the completion token. This completion
// handler matches the asynchronous operation's completion handler signature,
// which in this example is:
//
// void(std::error_code error, std::size_t)
//
// The initiation function object also receives any additional arguments
// required to start the operation. (Note: We could have instead passed these
// arguments as members in the initiaton function object. However, we should
// prefer to propagate them as function call arguments as this allows the
// completion token to optimise how they are passed. For example, a lazy
// future which defers initiation would need to make a decay-copy of the
// arguments, but when using a simple callback the arguments can be trivially
// forwarded straight through.)
template <typename CompletionHandler>
void operator()(CompletionHandler&& completion_handler, tcp::socket& socket,
const char* message, bool allow_partial_write) const
{
if (allow_partial_write)
{
// When delegating to an underlying operation we must take care to
// perfectly forward the completion handler. This ensures that our
// operation works correctly with move-only function objects as
// callbacks.
return socket.async_write_some(
asio::buffer(message, std::strlen(message)),
std::forward<CompletionHandler>(completion_handler));
}
else
{
// As above, we must perfectly forward the completion handler when calling
// the alternate underlying operation.
return asio::async_write(socket,
asio::buffer(message, std::strlen(message)),
std::forward<CompletionHandler>(completion_handler));
}
}
};
template <typename CompletionToken>
auto async_write_message(tcp::socket& socket,
const char* message, bool allow_partial_write,
CompletionToken&& token)
// The return type of the initiating function is deduced from the combination
// of:
//
// - the CompletionToken type,
// - the completion handler signature, and
// - the asynchronous operation's initiation function object.
//
// When the completion token is a simple callback, the return type is void.
// However, when the completion token is asio::yield_context (used for
// stackful coroutines) the return type would be std::size_t, and when the
// completion token is asio::use_future it would be std::future<std::size_t>.
// When the completion token is asio::deferred, the return type differs for
// each asynchronous operation.
//
// In C++11 we deduce the type from the call to asio::async_initiate.
-> decltype(
asio::async_initiate<
CompletionToken, void(std::error_code, std::size_t)>(
async_write_message_initiation(),
token, std::ref(socket), message, allow_partial_write))
{
// The asio::async_initiate function takes:
//
// - our initiation function object,
// - the completion token,
// - the completion handler signature, and
// - any additional arguments we need to initiate the operation.
//
// It then asks the completion token to create a completion handler (i.e. a
// callback) with the specified signature, and invoke the initiation function
// object with this completion handler as well as the additional arguments.
// The return value of async_initiate is the result of our operation's
// initiating function.
//
// Note that we wrap non-const reference arguments in std::reference_wrapper
// to prevent incorrect decay-copies of these objects.
return asio::async_initiate<
CompletionToken, void(std::error_code, std::size_t)>(
async_write_message_initiation(),
token, std::ref(socket), message, allow_partial_write);
}
//------------------------------------------------------------------------------
void test_callback()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using a lambda as a callback.
async_write_message(socket, "Testing callback\r\n", false,
[](const std::error_code& error, std::size_t n)
{
if (!error)
{
std::cout << n << " bytes transferred\n";
}
else
{
std::cout << "Error: " << error.message() << "\n";
}
});
io_context.run();
}
//------------------------------------------------------------------------------
void test_deferred()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using the deferred completion token. This
// token causes the operation's initiating function to package up the
// operation and its arguments to return a function object, which may then be
// used to launch the asynchronous operation.
auto op = async_write_message(socket,
"Testing deferred\r\n", false, asio::deferred);
// Launch the operation using a lambda as a callback.
std::move(op)(
[](const std::error_code& error, std::size_t n)
{
if (!error)
{
std::cout << n << " bytes transferred\n";
}
else
{
std::cout << "Error: " << error.message() << "\n";
}
});
io_context.run();
}
//------------------------------------------------------------------------------
void test_future()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using the use_future completion token.
// This token causes the operation's initiating function to return a future,
// which may be used to synchronously wait for the result of the operation.
std::future<std::size_t> f = async_write_message(
socket, "Testing future\r\n", false, asio::use_future);
io_context.run();
try
{
// Get the result of the operation.
std::size_t n = f.get();
std::cout << n << " bytes transferred\n";
}
catch (const std::exception& e)
{
std::cout << "Error: " << e.what() << "\n";
}
}
//------------------------------------------------------------------------------
int main()
{
test_callback();
test_deferred();
test_future();
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/operations/composed_4.cpp | //
// composed_4.cpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio/bind_executor.hpp>
#include <asio/deferred.hpp>
#include <asio/io_context.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/use_future.hpp>
#include <asio/write.hpp>
#include <cstring>
#include <functional>
#include <iostream>
#include <string>
#include <type_traits>
#include <utility>
using asio::ip::tcp;
// NOTE: This example requires the new asio::async_initiate function. For
// an example that works with the Networking TS style of completion tokens,
// please see an older version of asio.
//------------------------------------------------------------------------------
// In this composed operation we repackage an existing operation, but with a
// different completion handler signature. We will also intercept an empty
// message as an invalid argument, and propagate the corresponding error to the
// user. The asynchronous operation requirements are met by delegating
// responsibility to the underlying operation.
// In addition to determining the mechanism by which an asynchronous operation
// delivers its result, a completion token also determines the time when the
// operation commences. For example, when the completion token is a simple
// callback the operation commences before the initiating function returns.
// However, if the completion token's delivery mechanism uses a future, we
// might instead want to defer initiation of the operation until the returned
// future object is waited upon.
//
// To enable this, when implementing an asynchronous operation we must package
// the initiation step as a function object.
struct async_write_message_initiation
{
// The initiation function object's call operator is passed the concrete
// completion handler produced by the completion token. This completion
// handler matches the asynchronous operation's completion handler signature,
// which in this example is:
//
// void(std::error_code error)
//
// The initiation function object also receives any additional arguments
// required to start the operation. (Note: We could have instead passed these
// arguments as members in the initiaton function object. However, we should
// prefer to propagate them as function call arguments as this allows the
// completion token to optimise how they are passed. For example, a lazy
// future which defers initiation would need to make a decay-copy of the
// arguments, but when using a simple callback the arguments can be trivially
// forwarded straight through.)
template <typename CompletionHandler>
void operator()(CompletionHandler&& completion_handler,
tcp::socket& socket, const char* message) const
{
// The post operation has a completion handler signature of:
//
// void()
//
// and the async_write operation has a completion handler signature of:
//
// void(std::error_code error, std::size n)
//
// Both of these operations' completion handler signatures differ from our
// operation's completion handler signature. We will adapt our completion
// handler to these signatures by using std::bind, which drops the
// additional arguments.
//
// However, it is essential to the correctness of our composed operation
// that we preserve the executor of the user-supplied completion handler.
// The std::bind function will not do this for us, so we must do this by
// first obtaining the completion handler's associated executor (defaulting
// to the I/O executor - in this case the executor of the socket - if the
// completion handler does not have its own) ...
auto executor = asio::get_associated_executor(
completion_handler, socket.get_executor());
// ... and then binding this executor to our adapted completion handler
// using the asio::bind_executor function.
std::size_t length = std::strlen(message);
if (length == 0)
{
asio::post(
asio::bind_executor(executor,
std::bind(std::forward<CompletionHandler>(completion_handler),
asio::error::invalid_argument)));
}
else
{
asio::async_write(socket,
asio::buffer(message, length),
asio::bind_executor(executor,
std::bind(std::forward<CompletionHandler>(completion_handler),
std::placeholders::_1)));
}
}
};
template <typename CompletionToken>
auto async_write_message(tcp::socket& socket,
const char* message, CompletionToken&& token)
// The return type of the initiating function is deduced from the combination
// of:
//
// - the CompletionToken type,
// - the completion handler signature, and
// - the asynchronous operation's initiation function object.
//
// When the completion token is a simple callback, the return type is always
// void. In this example, when the completion token is asio::yield_context
// (used for stackful coroutines) the return type would also be void, as
// there is no non-error argument to the completion handler. When the
// completion token is asio::use_future it would be std::future<void>. When
// the completion token is asio::deferred, the return type differs for each
// asynchronous operation.
//
// In C++11 we deduce the type from the call to asio::async_initiate.
-> decltype(
asio::async_initiate<
CompletionToken, void(std::error_code)>(
async_write_message_initiation(),
token, std::ref(socket), message))
{
// The asio::async_initiate function takes:
//
// - our initiation function object,
// - the completion token,
// - the completion handler signature, and
// - any additional arguments we need to initiate the operation.
//
// It then asks the completion token to create a completion handler (i.e. a
// callback) with the specified signature, and invoke the initiation function
// object with this completion handler as well as the additional arguments.
// The return value of async_initiate is the result of our operation's
// initiating function.
//
// Note that we wrap non-const reference arguments in std::reference_wrapper
// to prevent incorrect decay-copies of these objects.
return asio::async_initiate<
CompletionToken, void(std::error_code)>(
async_write_message_initiation(),
token, std::ref(socket), message);
}
//------------------------------------------------------------------------------
void test_callback()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using a lambda as a callback.
async_write_message(socket, "",
[](const std::error_code& error)
{
if (!error)
{
std::cout << "Message sent\n";
}
else
{
std::cout << "Error: " << error.message() << "\n";
}
});
io_context.run();
}
//------------------------------------------------------------------------------
void test_deferred()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using the deferred completion token. This
// token causes the operation's initiating function to package up the
// operation and its arguments to return a function object, which may then be
// used to launch the asynchronous operation.
auto op = async_write_message(socket, "", asio::deferred);
// Launch the operation using a lambda as a callback.
std::move(op)(
[](const std::error_code& error)
{
if (!error)
{
std::cout << "Message sent\n";
}
else
{
std::cout << "Error: " << error.message() << "\n";
}
});
io_context.run();
}
//------------------------------------------------------------------------------
void test_future()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using the use_future completion token.
// This token causes the operation's initiating function to return a future,
// which may be used to synchronously wait for the result of the operation.
std::future<void> f = async_write_message(
socket, "", asio::use_future);
io_context.run();
try
{
// Get the result of the operation.
f.get();
std::cout << "Message sent\n";
}
catch (const std::exception& e)
{
std::cout << "Exception: " << e.what() << "\n";
}
}
//------------------------------------------------------------------------------
int main()
{
test_callback();
test_deferred();
test_future();
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/operations/composed_7.cpp | //
// composed_7.cpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio/compose.hpp>
#include <asio/deferred.hpp>
#include <asio/io_context.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/steady_timer.hpp>
#include <asio/use_future.hpp>
#include <asio/write.hpp>
#include <functional>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
using asio::ip::tcp;
// NOTE: This example requires the new asio::async_compose function. For
// an example that works with the Networking TS style of completion tokens,
// please see an older version of asio.
//------------------------------------------------------------------------------
// This composed operation shows composition of multiple underlying operations.
// It automatically serialises a message, using its I/O streams insertion
// operator, before sending it N times on the socket. To do this, it must
// allocate a buffer for the encoded message and ensure this buffer's validity
// until all underlying async_write operation complete. A one second delay is
// inserted prior to each write operation, using a steady_timer.
// In this example, the composed operation's logic is implemented as a state
// machine within a hand-crafted function object.
struct async_write_messages_implementation
{
// The implementation holds a reference to the socket as it is used for
// multiple async_write operations.
tcp::socket& socket_;
// The allocated buffer for the encoded message. The std::unique_ptr smart
// pointer is move-only, and as a consequence our implementation is also
// move-only.
std::unique_ptr<std::string> encoded_message_;
// The repeat count remaining.
std::size_t repeat_count_;
// A steady timer used for introducing a delay.
std::unique_ptr<asio::steady_timer> delay_timer_;
// To manage the cycle between the multiple underlying asychronous
// operations, our implementation is a state machine.
enum { starting, waiting, writing } state_;
// The first argument to our function object's call operator is a reference
// to the enclosing intermediate completion handler. This intermediate
// completion handler is provided for us by the asio::async_compose
// function, and takes care of all the details required to implement a
// conforming asynchronous operation. When calling an underlying asynchronous
// operation, we pass it this enclosing intermediate completion handler
// as the completion token.
//
// All arguments after the first must be defaulted to allow the state machine
// to be started, as well as to allow the completion handler to match the
// completion signature of both the async_write and steady_timer::async_wait
// operations.
template <typename Self>
void operator()(Self& self,
const std::error_code& error = std::error_code(),
std::size_t = 0)
{
if (!error)
{
switch (state_)
{
case starting:
case writing:
if (repeat_count_ > 0)
{
--repeat_count_;
state_ = waiting;
delay_timer_->expires_after(std::chrono::seconds(1));
delay_timer_->async_wait(std::move(self));
return; // Composed operation not yet complete.
}
break; // Composed operation complete, continue below.
case waiting:
state_ = writing;
asio::async_write(socket_,
asio::buffer(*encoded_message_), std::move(self));
return; // Composed operation not yet complete.
}
}
// This point is reached only on completion of the entire composed
// operation.
// Deallocate the encoded message and delay timer before calling the
// user-supplied completion handler.
encoded_message_.reset();
delay_timer_.reset();
// Call the user-supplied handler with the result of the operation.
self.complete(error);
}
};
template <typename T, typename CompletionToken>
auto async_write_messages(tcp::socket& socket,
const T& message, std::size_t repeat_count,
CompletionToken&& token)
// The return type of the initiating function is deduced from the combination
// of:
//
// - the CompletionToken type,
// - the completion handler signature, and
// - the asynchronous operation's initiation function object.
//
// When the completion token is a simple callback, the return type is always
// void. In this example, when the completion token is asio::yield_context
// (used for stackful coroutines) the return type would also be void, as
// there is no non-error argument to the completion handler. When the
// completion token is asio::use_future it would be std::future<void>. When
// the completion token is asio::deferred, the return type differs for each
// asynchronous operation.
//
// In C++11 we deduce the type from the call to asio::async_compose.
-> decltype(
asio::async_compose<
CompletionToken, void(std::error_code)>(
std::declval<async_write_messages_implementation>(),
token, socket))
{
// Encode the message and copy it into an allocated buffer. The buffer will
// be maintained for the lifetime of the composed asynchronous operation.
std::ostringstream os;
os << message;
std::unique_ptr<std::string> encoded_message(new std::string(os.str()));
// Create a steady_timer to be used for the delay between messages.
std::unique_ptr<asio::steady_timer> delay_timer(
new asio::steady_timer(socket.get_executor()));
// The asio::async_compose function takes:
//
// - our asynchronous operation implementation,
// - the completion token,
// - the completion handler signature, and
// - any I/O objects (or executors) used by the operation
//
// It then wraps our implementation in an intermediate completion handler
// that meets the requirements of a conforming asynchronous operation. This
// includes tracking outstanding work against the I/O executors associated
// with the operation (in this example, this is the socket's executor).
return asio::async_compose<
CompletionToken, void(std::error_code)>(
async_write_messages_implementation{
socket, std::move(encoded_message),
repeat_count, std::move(delay_timer),
async_write_messages_implementation::starting},
token, socket);
}
//------------------------------------------------------------------------------
void test_callback()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using a lambda as a callback.
async_write_messages(socket, "Testing callback\r\n", 5,
[](const std::error_code& error)
{
if (!error)
{
std::cout << "Messages sent\n";
}
else
{
std::cout << "Error: " << error.message() << "\n";
}
});
io_context.run();
}
//------------------------------------------------------------------------------
void test_deferred()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using the deferred completion token. This
// token causes the operation's initiating function to package up the
// operation and its arguments to return a function object, which may then be
// used to launch the asynchronous operation.
auto op = async_write_messages(socket,
"Testing deferred\r\n", 5, asio::deferred);
// Launch the operation using a lambda as a callback.
std::move(op)(
[](const std::error_code& error)
{
if (!error)
{
std::cout << "Messages sent\n";
}
else
{
std::cout << "Error: " << error.message() << "\n";
}
});
io_context.run();
}
//------------------------------------------------------------------------------
void test_future()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using the use_future completion token.
// This token causes the operation's initiating function to return a future,
// which may be used to synchronously wait for the result of the operation.
std::future<void> f = async_write_messages(
socket, "Testing future\r\n", 5, asio::use_future);
io_context.run();
try
{
// Get the result of the operation.
f.get();
std::cout << "Messages sent\n";
}
catch (const std::exception& e)
{
std::cout << "Error: " << e.what() << "\n";
}
}
//------------------------------------------------------------------------------
int main()
{
test_callback();
test_deferred();
test_future();
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/operations/composed_5.cpp | //
// composed_5.cpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio/deferred.hpp>
#include <asio/io_context.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/use_future.hpp>
#include <asio/write.hpp>
#include <functional>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
using asio::ip::tcp;
// NOTE: This example requires the new asio::async_initiate function. For
// an example that works with the Networking TS style of completion tokens,
// please see an older version of asio.
//------------------------------------------------------------------------------
// This composed operation automatically serialises a message, using its I/O
// streams insertion operator, before sending it on the socket. To do this, it
// must allocate a buffer for the encoded message and ensure this buffer's
// validity until the underlying async_write operation completes.
// In addition to determining the mechanism by which an asynchronous operation
// delivers its result, a completion token also determines the time when the
// operation commences. For example, when the completion token is a simple
// callback the operation commences before the initiating function returns.
// However, if the completion token's delivery mechanism uses a future, we
// might instead want to defer initiation of the operation until the returned
// future object is waited upon.
//
// To enable this, when implementing an asynchronous operation we must package
// the initiation step as a function object.
struct async_write_message_initiation
{
// The initiation function object's call operator is passed the concrete
// completion handler produced by the completion token. This completion
// handler matches the asynchronous operation's completion handler signature,
// which in this example is:
//
// void(std::error_code error)
//
// The initiation function object also receives any additional arguments
// required to start the operation. (Note: We could have instead passed these
// arguments as members in the initiaton function object. However, we should
// prefer to propagate them as function call arguments as this allows the
// completion token to optimise how they are passed. For example, a lazy
// future which defers initiation would need to make a decay-copy of the
// arguments, but when using a simple callback the arguments can be trivially
// forwarded straight through.)
template <typename CompletionHandler>
void operator()(CompletionHandler&& completion_handler,
tcp::socket& socket, std::unique_ptr<std::string> encoded_message) const
{
// In this example, the composed operation's intermediate completion
// handler is implemented as a hand-crafted function object, rather than
// using a lambda or std::bind.
struct intermediate_completion_handler
{
// The intermediate completion handler holds a reference to the socket so
// that it can obtain the I/O executor (see get_executor below).
tcp::socket& socket_;
// The allocated buffer for the encoded message. The std::unique_ptr
// smart pointer is move-only, and as a consequence our intermediate
// completion handler is also move-only.
std::unique_ptr<std::string> encoded_message_;
// The user-supplied completion handler.
typename std::decay<CompletionHandler>::type handler_;
// The function call operator matches the completion signature of the
// async_write operation.
void operator()(const std::error_code& error, std::size_t /*n*/)
{
// Deallocate the encoded message before calling the user-supplied
// completion handler.
encoded_message_.reset();
// Call the user-supplied handler with the result of the operation.
// The arguments must match the completion signature of our composed
// operation.
handler_(error);
}
// It is essential to the correctness of our composed operation that we
// preserve the executor of the user-supplied completion handler. With a
// hand-crafted function object we can do this by defining a nested type
// executor_type and member function get_executor. These obtain the
// completion handler's associated executor, and default to the I/O
// executor - in this case the executor of the socket - if the completion
// handler does not have its own.
using executor_type = asio::associated_executor_t<
typename std::decay<CompletionHandler>::type,
tcp::socket::executor_type>;
executor_type get_executor() const noexcept
{
return asio::get_associated_executor(
handler_, socket_.get_executor());
}
// Although not necessary for correctness, we may also preserve the
// allocator of the user-supplied completion handler. This is achieved by
// defining a nested type allocator_type and member function
// get_allocator. These obtain the completion handler's associated
// allocator, and default to std::allocator<void> if the completion
// handler does not have its own.
using allocator_type = asio::associated_allocator_t<
typename std::decay<CompletionHandler>::type,
std::allocator<void>>;
allocator_type get_allocator() const noexcept
{
return asio::get_associated_allocator(
handler_, std::allocator<void>{});
}
};
// Initiate the underlying async_write operation using our intermediate
// completion handler.
auto encoded_message_buffer = asio::buffer(*encoded_message);
asio::async_write(socket, encoded_message_buffer,
intermediate_completion_handler{socket, std::move(encoded_message),
std::forward<CompletionHandler>(completion_handler)});
}
};
template <typename T, typename CompletionToken>
auto async_write_message(tcp::socket& socket,
const T& message, CompletionToken&& token)
// The return type of the initiating function is deduced from the combination
// of:
//
// - the CompletionToken type,
// - the completion handler signature, and
// - the asynchronous operation's initiation function object.
//
// When the completion token is a simple callback, the return type is always
// void. In this example, when the completion token is asio::yield_context
// (used for stackful coroutines) the return type would also be void, as
// there is no non-error argument to the completion handler. When the
// completion token is asio::use_future it would be std::future<void>. When
// the completion token is asio::deferred, the return type differs for each
// asynchronous operation.
//
// In C++11 we deduce the type from the call to asio::async_initiate.
-> decltype(
asio::async_initiate<
CompletionToken, void(std::error_code)>(
async_write_message_initiation(), token,
std::ref(socket), std::declval<std::unique_ptr<std::string>>()))
{
// Encode the message and copy it into an allocated buffer. The buffer will
// be maintained for the lifetime of the asynchronous operation.
std::ostringstream os;
os << message;
std::unique_ptr<std::string> encoded_message(new std::string(os.str()));
// The asio::async_initiate function takes:
//
// - our initiation function object,
// - the completion token,
// - the completion handler signature, and
// - any additional arguments we need to initiate the operation.
//
// It then asks the completion token to create a completion handler (i.e. a
// callback) with the specified signature, and invoke the initiation function
// object with this completion handler as well as the additional arguments.
// The return value of async_initiate is the result of our operation's
// initiating function.
//
// Note that we wrap non-const reference arguments in std::reference_wrapper
// to prevent incorrect decay-copies of these objects.
return asio::async_initiate<
CompletionToken, void(std::error_code)>(
async_write_message_initiation(), token,
std::ref(socket), std::move(encoded_message));
}
//------------------------------------------------------------------------------
void test_callback()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using a lambda as a callback.
async_write_message(socket, 123456,
[](const std::error_code& error)
{
if (!error)
{
std::cout << "Message sent\n";
}
else
{
std::cout << "Error: " << error.message() << "\n";
}
});
io_context.run();
}
//------------------------------------------------------------------------------
void test_deferred()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using the deferred completion token. This
// token causes the operation's initiating function to package up the
// operation and its arguments to return a function object, which may then be
// used to launch the asynchronous operation.
auto op = async_write_message(socket,
std::string("abcdef"), asio::deferred);
// Launch the operation using a lambda as a callback.
std::move(op)(
[](const std::error_code& error)
{
if (!error)
{
std::cout << "Message sent\n";
}
else
{
std::cout << "Error: " << error.message() << "\n";
}
});
io_context.run();
}
//------------------------------------------------------------------------------
void test_future()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using the use_future completion token.
// This token causes the operation's initiating function to return a future,
// which may be used to synchronously wait for the result of the operation.
std::future<void> f = async_write_message(
socket, 654.321, asio::use_future);
io_context.run();
try
{
// Get the result of the operation.
f.get();
std::cout << "Message sent\n";
}
catch (const std::exception& e)
{
std::cout << "Exception: " << e.what() << "\n";
}
}
//------------------------------------------------------------------------------
int main()
{
test_callback();
test_deferred();
test_future();
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/operations/composed_3.cpp | //
// composed_3.cpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio/bind_executor.hpp>
#include <asio/deferred.hpp>
#include <asio/io_context.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/use_future.hpp>
#include <asio/write.hpp>
#include <cstring>
#include <functional>
#include <iostream>
#include <string>
#include <type_traits>
#include <utility>
using asio::ip::tcp;
// NOTE: This example requires the new asio::async_initiate function. For
// an example that works with the Networking TS style of completion tokens,
// please see an older version of asio.
//------------------------------------------------------------------------------
// In this composed operation we repackage an existing operation, but with a
// different completion handler signature. The asynchronous operation
// requirements are met by delegating responsibility to the underlying
// operation.
// In addition to determining the mechanism by which an asynchronous operation
// delivers its result, a completion token also determines the time when the
// operation commences. For example, when the completion token is a simple
// callback the operation commences before the initiating function returns.
// However, if the completion token's delivery mechanism uses a future, we
// might instead want to defer initiation of the operation until the returned
// future object is waited upon.
//
// To enable this, when implementing an asynchronous operation we must package
// the initiation step as a function object.
struct async_write_message_initiation
{
// The initiation function object's call operator is passed the concrete
// completion handler produced by the completion token. This completion
// handler matches the asynchronous operation's completion handler signature,
// which in this example is:
//
// void(std::error_code error)
//
// The initiation function object also receives any additional arguments
// required to start the operation. (Note: We could have instead passed these
// arguments as members in the initiaton function object. However, we should
// prefer to propagate them as function call arguments as this allows the
// completion token to optimise how they are passed. For example, a lazy
// future which defers initiation would need to make a decay-copy of the
// arguments, but when using a simple callback the arguments can be trivially
// forwarded straight through.)
template <typename CompletionHandler>
void operator()(CompletionHandler&& completion_handler,
tcp::socket& socket, const char* message) const
{
// The async_write operation has a completion handler signature of:
//
// void(std::error_code error, std::size n)
//
// This differs from our operation's signature in that it is also passed
// the number of bytes transferred as an argument of type std::size_t. We
// will adapt our completion handler to async_write's completion handler
// signature by using std::bind, which drops the additional argument.
//
// However, it is essential to the correctness of our composed operation
// that we preserve the executor of the user-supplied completion handler.
// The std::bind function will not do this for us, so we must do this by
// first obtaining the completion handler's associated executor (defaulting
// to the I/O executor - in this case the executor of the socket - if the
// completion handler does not have its own) ...
auto executor = asio::get_associated_executor(
completion_handler, socket.get_executor());
// ... and then binding this executor to our adapted completion handler
// using the asio::bind_executor function.
asio::async_write(socket,
asio::buffer(message, std::strlen(message)),
asio::bind_executor(executor,
std::bind(std::forward<CompletionHandler>(
completion_handler), std::placeholders::_1)));
}
};
template <typename CompletionToken>
auto async_write_message(tcp::socket& socket,
const char* message, CompletionToken&& token)
// The return type of the initiating function is deduced from the combination
// of:
//
// - the CompletionToken type,
// - the completion handler signature, and
// - the asynchronous operation's initiation function object.
//
// When the completion token is a simple callback, the return type is always
// void. In this example, when the completion token is asio::yield_context
// (used for stackful coroutines) the return type would also be void, as
// there is no non-error argument to the completion handler. When the
// completion token is asio::use_future it would be std::future<void>. When
// the completion token is asio::deferred, the return type differs for each
// asynchronous operation.
//
// In C++11 we deduce the type from the call to asio::async_initiate.
-> decltype(
asio::async_initiate<
CompletionToken, void(std::error_code)>(
async_write_message_initiation(),
token, std::ref(socket), message))
{
// The asio::async_initiate function takes:
//
// - our initiation function object,
// - the completion token,
// - the completion handler signature, and
// - any additional arguments we need to initiate the operation.
//
// It then asks the completion token to create a completion handler (i.e. a
// callback) with the specified signature, and invoke the initiation function
// object with this completion handler as well as the additional arguments.
// The return value of async_initiate is the result of our operation's
// initiating function.
//
// Note that we wrap non-const reference arguments in std::reference_wrapper
// to prevent incorrect decay-copies of these objects.
return asio::async_initiate<
CompletionToken, void(std::error_code)>(
async_write_message_initiation(),
token, std::ref(socket), message);
}
//------------------------------------------------------------------------------
void test_callback()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using a lambda as a callback.
async_write_message(socket, "Testing callback\r\n",
[](const std::error_code& error)
{
if (!error)
{
std::cout << "Message sent\n";
}
else
{
std::cout << "Error: " << error.message() << "\n";
}
});
io_context.run();
}
//------------------------------------------------------------------------------
void test_deferred()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using the deferred completion token. This
// token causes the operation's initiating function to package up the
// operation and its arguments to return a function object, which may then be
// used to launch the asynchronous operation.
auto op = async_write_message(socket,
"Testing deferred\r\n", asio::deferred);
// Launch the operation using a lambda as a callback.
std::move(op)(
[](const std::error_code& error)
{
if (!error)
{
std::cout << "Message sent\n";
}
else
{
std::cout << "Error: " << error.message() << "\n";
}
});
io_context.run();
}
//------------------------------------------------------------------------------
void test_future()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using the use_future completion token.
// This token causes the operation's initiating function to return a future,
// which may be used to synchronously wait for the result of the operation.
std::future<void> f = async_write_message(
socket, "Testing future\r\n", asio::use_future);
io_context.run();
// Get the result of the operation.
try
{
// Get the result of the operation.
f.get();
std::cout << "Message sent\n";
}
catch (const std::exception& e)
{
std::cout << "Error: " << e.what() << "\n";
}
}
//------------------------------------------------------------------------------
int main()
{
test_callback();
test_deferred();
test_future();
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/operations/composed_1.cpp | //
// composed_1.cpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio/deferred.hpp>
#include <asio/io_context.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/use_future.hpp>
#include <asio/write.hpp>
#include <cstring>
#include <iostream>
#include <string>
#include <type_traits>
#include <utility>
using asio::ip::tcp;
//------------------------------------------------------------------------------
// This is the simplest example of a composed asynchronous operation, where we
// simply repackage an existing operation. The asynchronous operation
// requirements are met by delegating responsibility to the underlying
// operation.
template <typename CompletionToken>
auto async_write_message(tcp::socket& socket,
const char* message, CompletionToken&& token)
// The return type of the initiating function is deduced from the combination
// of:
//
// - the CompletionToken type,
// - the completion handler signature, and
// - the asynchronous operation's initiation function object.
//
// When the completion token is a simple callback, the return type is void.
// However, when the completion token is asio::yield_context (used for
// stackful coroutines) the return type would be std::size_t, and when the
// completion token is asio::use_future it would be std::future<std::size_t>.
// When the completion token is asio::deferred, the return type differs for
// each asynchronous operation.
//
// In this example we are trivially delegating to an underlying asynchronous
// operation, so we can deduce the return type from that.
-> decltype(
asio::async_write(socket,
asio::buffer(message, std::strlen(message)),
std::forward<CompletionToken>(token)))
{
// When delegating to the underlying operation we must take care to perfectly
// forward the completion token. This ensures that our operation works
// correctly with move-only function objects as callbacks, as well as other
// completion token types.
return asio::async_write(socket,
asio::buffer(message, std::strlen(message)),
std::forward<CompletionToken>(token));
}
//------------------------------------------------------------------------------
void test_callback()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using a lambda as a callback.
async_write_message(socket, "Testing callback\r\n",
[](const std::error_code& error, std::size_t n)
{
if (!error)
{
std::cout << n << " bytes transferred\n";
}
else
{
std::cout << "Error: " << error.message() << "\n";
}
});
io_context.run();
}
//------------------------------------------------------------------------------
void test_deferred()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using the deferred completion token. This
// token causes the operation's initiating function to package up the
// operation and its arguments to return a function object, which may then be
// used to launch the asynchronous operation.
auto op = async_write_message(socket,
"Testing deferred\r\n", asio::deferred);
// Launch the operation using a lambda as a callback.
std::move(op)(
[](const std::error_code& error, std::size_t n)
{
if (!error)
{
std::cout << n << " bytes transferred\n";
}
else
{
std::cout << "Error: " << error.message() << "\n";
}
});
io_context.run();
}
//------------------------------------------------------------------------------
void test_future()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using the use_future completion token.
// This token causes the operation's initiating function to return a future,
// which may be used to synchronously wait for the result of the operation.
std::future<std::size_t> f = async_write_message(
socket, "Testing future\r\n", asio::use_future);
io_context.run();
try
{
// Get the result of the operation.
std::size_t n = f.get();
std::cout << n << " bytes transferred\n";
}
catch (const std::exception& e)
{
std::cout << "Error: " << e.what() << "\n";
}
}
//------------------------------------------------------------------------------
int main()
{
test_callback();
test_deferred();
test_future();
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/deferred/deferred_1.cpp | //
// deferred_1.cpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio.hpp>
#include <iostream>
using asio::deferred;
int main()
{
asio::io_context ctx;
asio::steady_timer timer(ctx);
timer.expires_after(std::chrono::seconds(1));
auto deferred_op = timer.async_wait(deferred);
std::move(deferred_op)(
[](std::error_code ec)
{
std::cout << "timer wait finished: " << ec.message() << "\n";
}
);
ctx.run();
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/deferred/deferred_2.cpp | //
// deferred_2.cpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio.hpp>
#include <iostream>
using asio::deferred;
int main()
{
asio::io_context ctx;
asio::steady_timer timer(ctx);
timer.expires_after(std::chrono::seconds(1));
auto deferred_op = timer.async_wait(
deferred(
[&](std::error_code ec)
{
std::cout << "first timer wait finished: " << ec.message() << "\n";
timer.expires_after(std::chrono::seconds(1));
return timer.async_wait(deferred);
}
)
);
std::move(deferred_op)(
[](std::error_code ec)
{
std::cout << "second timer wait finished: " << ec.message() << "\n";
}
);
ctx.run();
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/iostreams/daytime_server.cpp | //
// daytime_server.cpp
// ~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <ctime>
#include <iostream>
#include <string>
#include <asio.hpp>
using asio::ip::tcp;
std::string make_daytime_string()
{
using namespace std; // For time_t, time and ctime;
time_t now = time(0);
return ctime(&now);
}
int main()
{
try
{
asio::io_context io_context;
tcp::endpoint endpoint(tcp::v4(), 13);
tcp::acceptor acceptor(io_context, endpoint);
for (;;)
{
tcp::iostream stream;
std::error_code ec;
acceptor.accept(stream.socket(), ec);
if (!ec)
{
stream << make_daytime_string();
}
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/iostreams/daytime_client.cpp | //
// daytime_client.cpp
// ~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <iostream>
#include <string>
#include <asio.hpp>
using asio::ip::tcp;
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: daytime_client <host>" << std::endl;
return 1;
}
tcp::iostream s(argv[1], "daytime");
if (!s)
{
std::cout << "Unable to connect: " << s.error().message() << std::endl;
return 1;
}
std::string line;
std::getline(s, line);
std::cout << line << std::endl;
}
catch (std::exception& e)
{
std::cout << "Exception: " << e.what() << std::endl;
}
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/iostreams/http_client.cpp | //
// http_client.cpp
// ~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <iostream>
#include <istream>
#include <ostream>
#include <string>
#include <asio/ip/tcp.hpp>
using asio::ip::tcp;
int main(int argc, char* argv[])
{
try
{
if (argc != 3)
{
std::cout << "Usage: http_client <server> <path>\n";
std::cout << "Example:\n";
std::cout << " http_client www.boost.org /LICENSE_1_0.txt\n";
return 1;
}
asio::ip::tcp::iostream s;
// The entire sequence of I/O operations must complete within 60 seconds.
// If an expiry occurs, the socket is automatically closed and the stream
// becomes bad.
s.expires_after(std::chrono::seconds(60));
// Establish a connection to the server.
s.connect(argv[1], "http");
if (!s)
{
std::cout << "Unable to connect: " << s.error().message() << "\n";
return 1;
}
// Send the request. We specify the "Connection: close" header so that the
// server will close the socket after transmitting the response. This will
// allow us to treat all data up until the EOF as the content.
s << "GET " << argv[2] << " HTTP/1.0\r\n";
s << "Host: " << argv[1] << "\r\n";
s << "Accept: */*\r\n";
s << "Connection: close\r\n\r\n";
// By default, the stream is tied with itself. This means that the stream
// automatically flush the buffered output before attempting a read. It is
// not necessary not explicitly flush the stream at this point.
// Check that response is OK.
std::string http_version;
s >> http_version;
unsigned int status_code;
s >> status_code;
std::string status_message;
std::getline(s, status_message);
if (!s || http_version.substr(0, 5) != "HTTP/")
{
std::cout << "Invalid response\n";
return 1;
}
if (status_code != 200)
{
std::cout << "Response returned with status code " << status_code << "\n";
return 1;
}
// Process the response headers, which are terminated by a blank line.
std::string header;
while (std::getline(s, header) && header != "\r")
std::cout << header << "\n";
std::cout << "\n";
// Write the remaining data to output.
std::cout << s.rdbuf();
}
catch (std::exception& e)
{
std::cout << "Exception: " << e.what() << "\n";
}
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/parallel_group/wait_for_one_success.cpp | //
// wait_for_one_error.cpp
// ~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio.hpp>
#include <asio/experimental/parallel_group.hpp>
#include <iostream>
#if defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
int main()
{
asio::io_context ctx;
asio::posix::stream_descriptor in(ctx, ::dup(STDIN_FILENO));
asio::steady_timer timer(ctx, std::chrono::seconds(5));
char data[1024];
asio::experimental::make_parallel_group(
in.async_read_some(asio::buffer(data)),
timer.async_wait()
).async_wait(
asio::experimental::wait_for_one_success(),
[](
std::array<std::size_t, 2> completion_order,
std::error_code ec1, std::size_t n1,
std::error_code ec2
)
{
switch (completion_order[0])
{
case 0:
{
std::cout << "descriptor finished: " << ec1 << ", " << n1 << "\n";
}
break;
case 1:
{
std::cout << "timer finished: " << ec2 << "\n";
}
break;
}
}
);
ctx.run();
}
#else // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
int main() {}
#endif // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/parallel_group/wait_for_one_error.cpp | //
// wait_for_one_error.cpp
// ~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio.hpp>
#include <asio/experimental/parallel_group.hpp>
#include <iostream>
#if defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
int main()
{
asio::io_context ctx;
asio::posix::stream_descriptor in(ctx, ::dup(STDIN_FILENO));
asio::steady_timer timer(ctx, std::chrono::seconds(5));
char data[1024];
asio::experimental::make_parallel_group(
in.async_read_some(asio::buffer(data)),
timer.async_wait()
).async_wait(
asio::experimental::wait_for_one_error(),
[](
std::array<std::size_t, 2> completion_order,
std::error_code ec1, std::size_t n1,
std::error_code ec2
)
{
switch (completion_order[0])
{
case 0:
{
std::cout << "descriptor finished: " << ec1 << ", " << n1 << "\n";
}
break;
case 1:
{
std::cout << "timer finished: " << ec2 << "\n";
}
break;
}
}
);
ctx.run();
}
#else // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
int main() {}
#endif // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/parallel_group/wait_for_all.cpp | //
// wait_for_all.cpp
// ~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio.hpp>
#include <asio/experimental/parallel_group.hpp>
#include <iostream>
#ifdef ASIO_HAS_POSIX_STREAM_DESCRIPTOR
int main()
{
asio::io_context ctx;
asio::posix::stream_descriptor in(ctx, ::dup(STDIN_FILENO));
asio::steady_timer timer(ctx, std::chrono::seconds(5));
char data[1024];
asio::experimental::make_parallel_group(
in.async_read_some(asio::buffer(data)),
timer.async_wait()
).async_wait(
asio::experimental::wait_for_all(),
[](
std::array<std::size_t, 2> completion_order,
std::error_code ec1, std::size_t n1,
std::error_code ec2
)
{
switch (completion_order[0])
{
case 0:
{
std::cout << "descriptor finished: " << ec1 << ", " << n1 << "\n";
}
break;
case 1:
{
std::cout << "timer finished: " << ec2 << "\n";
}
break;
}
}
);
ctx.run();
}
#else // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
int main() {}
#endif // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/parallel_group/wait_for_one.cpp | //
// wait_for_one.cpp
// ~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio.hpp>
#include <asio/experimental/parallel_group.hpp>
#include <iostream>
#if defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
int main()
{
asio::io_context ctx;
asio::posix::stream_descriptor in(ctx, ::dup(STDIN_FILENO));
asio::steady_timer timer(ctx, std::chrono::seconds(5));
char data[1024];
asio::experimental::make_parallel_group(
in.async_read_some(asio::buffer(data)),
timer.async_wait()
).async_wait(
asio::experimental::wait_for_one(),
[](
std::array<std::size_t, 2> completion_order,
std::error_code ec1, std::size_t n1,
std::error_code ec2
)
{
switch (completion_order[0])
{
case 0:
{
std::cout << "descriptor finished: " << ec1 << ", " << n1 << "\n";
}
break;
case 1:
{
std::cout << "timer finished: " << ec2 << "\n";
}
break;
}
}
);
ctx.run();
}
#else // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
int main() {}
#endif // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/parallel_group/ranged_wait_for_all.cpp | //
// ranged_wait_for_all.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio.hpp>
#include <asio/experimental/parallel_group.hpp>
#include <iostream>
#include <vector>
#ifdef ASIO_HAS_POSIX_STREAM_DESCRIPTOR
int main()
{
asio::io_context ctx;
asio::posix::stream_descriptor out(ctx, ::dup(STDOUT_FILENO));
asio::posix::stream_descriptor err(ctx, ::dup(STDERR_FILENO));
using op_type = decltype(
out.async_write_some(asio::buffer("", 0))
);
std::vector<op_type> ops;
ops.push_back(
out.async_write_some(asio::buffer("first\r\n", 7))
);
ops.push_back(
err.async_write_some(asio::buffer("second\r\n", 8))
);
asio::experimental::make_parallel_group(ops).async_wait(
asio::experimental::wait_for_all(),
[](
std::vector<std::size_t> completion_order,
std::vector<std::error_code> ec,
std::vector<std::size_t> n
)
{
for (std::size_t i = 0; i < completion_order.size(); ++i)
{
std::size_t idx = completion_order[i];
std::cout << "operation " << idx << " finished: ";
std::cout << ec[idx] << ", " << n[idx] << "\n";
}
}
);
ctx.run();
}
#else // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
int main() {}
#endif // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/tutorial/daytime_dox.txt | //
// Copyright (c) 2003-2024 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)
//
/**
\page tutdaytime1 Daytime.1 - A synchronous TCP daytime client
This tutorial program shows how to use asio to implement a client application
with TCP.
\dontinclude daytime1/client.cpp
\skip #include
We start by including the necessary header files.
\until asio.hpp
The purpose of this application is to access a daytime service,
so we need the user to specify the server.
\until }
All programs that use asio need to have at least one I/O execution context,
such as an asio::io_context object.
\until asio::io_context
We need to turn the server name that was specified as a parameter to the
application, into a TCP endpoint. To do this we use an
asio::ip::tcp::resolver object.
\until tcp::resolver
A resolver takes a host name and service name and turns them into a list of
endpoints. We perform a resolve call using the name of the server, specified in
<tt>argv[1]</tt>, and the name of the service, in this case <tt>"daytime"</tt>.
The list of endpoints is returned using an object of type
asio::ip::tcp::resolver::results_type. This object is a range, with begin() and
end() member functions that may be used for iterating over the results.
\until resolver.resolve
Now we create and connect the socket. The list of endpoints obtained above may
contain both IPv4 and IPv6 endpoints, so we need to try each of them until we
find one that works. This keeps the client program independent of a specific IP
version. The asio::connect() function does this for us automatically.
\until asio::connect
The connection is open. All we need to do now is read the response from the
daytime service.
We use a <tt>std::array</tt> to hold the received data. The asio::buffer()
function automatically determines the size of the array to help prevent buffer
overruns. Instead of a <tt>std::array</tt>, we could have used a <tt>char
[]</tt> or <tt>std::vector</tt>.
\until read_some
When the server closes the connection, the asio::ip::tcp::socket::read_some()
function will exit with the asio::error::eof error, which is how we know to
exit the loop.
\until }
Finally, handle any exceptions that may have been thrown.
\until }
\until }
See the \ref tutdaytime1src "full source listing" \n
Return to the \ref index "tutorial index" \n
Next: \ref tutdaytime2
*/
/**
\page tutdaytime1src Source listing for Daytime.1
\include daytime1/client.cpp
Return to \ref tutdaytime1
*/
/**
\page tutdaytime2 Daytime.2 - A synchronous TCP daytime server
This tutorial program shows how to use asio to implement a server application
with TCP.
\dontinclude daytime2/server.cpp
\skip #include
\until using
We define the function <tt>make_daytime_string()</tt> to create the string to
be sent back to the client. This function will be reused in all of our daytime
server applications.
\until asio::io_context
A asio::ip::tcp::acceptor object needs to be created to listen
for new connections. It is initialised to listen on TCP port 13, for IP version 4.
\until tcp::acceptor
This is an iterative server, which means that it will handle one
connection at a time. Create a socket that will represent the connection to the
client, and then wait for a connection.
\until acceptor.accept
A client is accessing our service. Determine the current time
and transfer this information to the client.
\until }
\until }
Finally, handle any exceptions.
\until }
\until }
See the \ref tutdaytime2src "full source listing" \n
Return to the \ref index "tutorial index" \n
Previous: \ref tutdaytime1 \n
Next: \ref tutdaytime3
*/
/**
\page tutdaytime2src Source listing for Daytime.2
\include daytime2/server.cpp
Return to \ref tutdaytime2
*/
/**
\page tutdaytime3 Daytime.3 - An asynchronous TCP daytime server
\section tutdaytime3funcmain The main() function
\dontinclude daytime3/server.cpp
\skip int main()
\until try
\until {
We need to create a server object to accept incoming client connections. The
asio::io_context object provides I/O services, such as sockets, that the
server object will use.
\until tcp_server
Run the asio::io_context object so that it will perform asynchronous operations
on your behalf.
\until return 0;
\until }
\section tutdaytime3classtcp_server The tcp_server class
\dontinclude daytime3/server.cpp
\skip class tcp_server
\until public:
The constructor initialises an acceptor to listen on TCP port 13.
\until private:
The function <tt>start_accept()</tt> creates a socket and initiates an
asynchronous accept operation to wait for a new connection.
\until }
The function <tt>handle_accept()</tt> is called when the asynchronous accept
operation initiated by <tt>start_accept()</tt> finishes. It services the client
request, and then calls <tt>start_accept()</tt> to initiate the next accept
operation.
\until }
\until }
\section tutdaytime3classtcp_connection The tcp_connection class
We will use <tt>shared_ptr</tt> and <tt>enable_shared_from_this</tt> because we
want to keep the <tt>tcp_connection</tt> object alive as long as there is an
operation that refers to it.
\dontinclude daytime3/server.cpp
\skip class tcp_connection
\until shared_ptr
\until }
\until }
In the function <tt>start()</tt>, we call asio::async_write() to serve the data
to the client. Note that we are using asio::async_write(), rather than
asio::ip::tcp::socket::async_write_some(), to ensure that the entire block of
data is sent.
\until {
The data to be sent is stored in the class member <tt>message_</tt> as we need
to keep the data valid until the asynchronous operation is complete.
\until message_
When initiating the asynchronous operation, and if using @c std::bind, you
must specify only the arguments that match the handler's parameter list. In
this program, both of the argument placeholders (asio::placeholders::error and
asio::placeholders::bytes_transferred) could potentially have been removed,
since they are not being used in <tt>handle_write()</tt>.
\until placeholders::bytes_transferred
Any further actions for this client connection are now the responsibility of
<tt>handle_write()</tt>.
\until };
\section tutdaytime3remunused Removing unused handler parameters
You may have noticed that the <tt>error</tt>, and <tt>bytes_transferred</tt>
parameters are not used in the body of the <tt>handle_write()</tt> function. If
parameters are not needed, it is possible to remove them from the function so
that it looks like:
\code
void handle_write()
{
}
\endcode
The asio::async_write() call used to initiate the call can then be changed to
just:
\code
asio::async_write(socket_, asio::buffer(message_),
std::bind(&tcp_connection::handle_write, shared_from_this()));
\endcode
See the \ref tutdaytime3src "full source listing" \n
Return to the \ref index "tutorial index" \n
Previous: \ref tutdaytime2 \n
Next: \ref tutdaytime4
*/
/**
\page tutdaytime3src Source listing for Daytime.3
\include daytime3/server.cpp
Return to \ref tutdaytime3
*/
/**
\page tutdaytime4 Daytime.4 - A synchronous UDP daytime client
This tutorial program shows how to use asio to implement a client application
with UDP.
\dontinclude daytime4/client.cpp
\skip #include
\until using asio::ip::udp;
The start of the application is essentially the same as for the TCP daytime
client.
\until asio::io_context
We use an asio::ip::udp::resolver object to find the correct remote endpoint to
use based on the host and service names. The query is restricted to return only
IPv4 endpoints by the asio::ip::udp::v4() argument.
\until udp::v4
The asio::ip::udp::resolver::resolve() function is guaranteed to return at
least one endpoint in the list if it does not fail. This means it is safe to
dereference the return value directly.
Since UDP is datagram-oriented, we will not be using a stream socket. Create an
asio::ip::udp::socket and initiate contact with the remote endpoint.
\until receiver_endpoint
Now we need to be ready to accept whatever the server sends back to us. The
endpoint on our side that receives the server's response will be initialised by
asio::ip::udp::socket::receive_from().
\until }
Finally, handle any exceptions that may have been thrown.
\until }
\until }
See the \ref tutdaytime4src "full source listing" \n
Return to the \ref index "tutorial index" \n
Previous: \ref tutdaytime3 \n
Next: \ref tutdaytime5
*/
/**
\page tutdaytime4src Source listing for Daytime.4
\include daytime4/client.cpp
Return to \ref tutdaytime4
*/
/**
\page tutdaytime5 Daytime.5 - A synchronous UDP daytime server
This tutorial program shows how to use asio to implement a server application
with UDP.
\dontinclude daytime5/server.cpp
\skip int main()
\until asio::io_context
Create an asio::ip::udp::socket object to receive requests on UDP port 13.
\until udp::socket
Wait for a client to initiate contact with us. The remote_endpoint object will
be populated by asio::ip::udp::socket::receive_from().
\until receive_from
Determine what we are going to send back to the client.
\until std::string message
Send the response to the remote_endpoint.
\until }
\until }
Finally, handle any exceptions.
\until }
\until }
See the \ref tutdaytime5src "full source listing" \n
Return to the \ref index "tutorial index" \n
Previous: \ref tutdaytime4 \n
Next: \ref tutdaytime6
*/
/**
\page tutdaytime5src Source listing for Daytime.5
\include daytime5/server.cpp
Return to \ref tutdaytime5
*/
/**
\page tutdaytime6 Daytime.6 - An asynchronous UDP daytime server
\section tutdaytime6funcmain The main() function
\dontinclude daytime6/server.cpp
\skip int main()
\until try
\until {
Create a server object to accept incoming client requests, and run
the asio::io_context object.
\until return 0;
\until }
\section tutdaytime6classudp_server The udp_server class
\dontinclude daytime6/server.cpp
\skip class udp_server
\until public:
The constructor initialises a socket to listen on UDP port 13.
\until private:
\until {
The function asio::ip::udp::socket::async_receive_from() will cause the
application to listen in the background for a new request. When such a request
is received, the asio::io_context object will invoke the
<tt>handle_receive()</tt> function with two arguments: a value of type
std::error_code indicating whether the operation succeeded or failed, and a
<tt>size_t</tt> value <tt>bytes_transferred</tt> specifying the number of bytes
received.
\until }
The function <tt>handle_receive()</tt> will service the client request.
\until {
The <tt>error</tt> parameter contains the result of the asynchronous operation.
Since we only provide the 1-byte <tt>recv_buffer_</tt> to contain the client's
request, the asio::io_context object would return an error if the client sent
anything larger. We can ignore such an error if it comes up.
\until {
Determine what we are going to send.
\until make_daytime_string()
We now call asio::ip::udp::socket::async_send_to() to serve the data to the
client.
\until asio::placeholders::bytes_transferred
When initiating the asynchronous operation, and if using @c std::bind, you
must specify only the arguments that match the handler's parameter list. In
this program, both of the argument placeholders (asio::placeholders::error and
asio::placeholders::bytes_transferred) could potentially have been removed.
Start listening for the next client request.
\until start_receive
Any further actions for this client request are now the responsibility of
<tt>handle_send()</tt>.
\until }
\until }
The function <tt>handle_send()</tt> is invoked after the service request has
been completed.
\until }
\until }
See the \ref tutdaytime6src "full source listing" \n
Return to the \ref index "tutorial index" \n
Previous: \ref tutdaytime5 \n
Next: \ref tutdaytime7
*/
/**
\page tutdaytime6src Source listing for Daytime.6
\include daytime6/server.cpp
Return to \ref tutdaytime6
*/
/**
\page tutdaytime7 Daytime.7 - A combined TCP/UDP asynchronous server
This tutorial program shows how to combine the two asynchronous servers that we
have just written, into a single server application.
\section tutdaytime7funcmain The main() function
\dontinclude daytime7/server.cpp
\skip int main()
\until asio::io_context
We will begin by creating a server object to accept a TCP client connection.
\until tcp_server
We also need a server object to accept a UDP client request.
\until udp_server
We have created two lots of work for the asio::io_context object to do.
\until return 0;
\until }
\section tutdaytime7classtcp The tcp_connection and tcp_server classes
The following two classes are taken from \ref tutdaytime3 "Daytime.3".
\dontinclude daytime7/server.cpp
\skip class tcp_connection
\until };
\until };
\section tutdaytime7classudp The udp_server class
Similarly, this next class is taken from the
\ref tutdaytime6 "previous tutorial step".
\dontinclude daytime7/server.cpp
\skip class udp_server
\until };
See the \ref tutdaytime7src "full source listing" \n
Return to the \ref index "tutorial index" \n
Previous: \ref tutdaytime6
*/
/**
\page tutdaytime7src Source listing for Daytime.7
\include daytime7/server.cpp
Return to \ref tutdaytime7
*/
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/tutorial/index_dox.txt | //
// Copyright (c) 2003-2024 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)
//
/**
\mainpage asio Tutorial
\section tuttimer Basic Skills
The tutorial programs in this first section introduce the fundamental concepts
required to use the asio toolkit. Before plunging into the complex world of
network programming, these tutorial programs illustrate the basic skills using
simple asynchronous timers.
\li \ref tuttimer1
\li \ref tuttimer2
\li \ref tuttimer3
\li \ref tuttimer4
\li \ref tuttimer5
\section tutdaytime Introduction to Sockets
The tutorial programs in this section show how to use asio to develop simple
client and server programs. These tutorial programs are based around the <a
href="http://www.ietf.org/rfc/rfc867.txt">daytime</a> protocol, which supports
both TCP and UDP.
The first three tutorial programs implement the daytime protocol using TCP.
\li \ref tutdaytime1
\li \ref tutdaytime2
\li \ref tutdaytime3
The next three tutorial programs implement the daytime protocol using UDP.
\li \ref tutdaytime4
\li \ref tutdaytime5
\li \ref tutdaytime6
The last tutorial program in this section demonstrates how asio allows the TCP
and UDP servers to be easily combined into a single program.
\li \ref tutdaytime7
*/
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/tutorial/timer_dox.txt | //
// Copyright (c) 2003-2024 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)
//
/**
\page tuttimer1 Timer.1 - Using a timer synchronously
This tutorial program introduces asio by showing how to perform a blocking
wait on a timer.
\dontinclude timer1/timer.cpp
\skip #include
We start by including the necessary header files.
All of the asio classes can be used by simply including the <tt>"asio.hpp"</tt>
header file.
\until asio.hpp
All programs that use asio need to have at least one I/O execution context,
such as an asio::io_context or asio::thread_pool object. An I/O execution
context provides access to I/O functionality. We declare an object of type
asio::io_context first thing in the main function.
\until asio::io_context
Next we declare an object of type asio::steady_timer. The core asio classes
that provide I/O functionality (or as in this case timer functionality) always
take an executor, or a reference to an execution context (such as
asio::io_context), as their first constructor argument. The second argument to
the constructor sets the timer to expire 5 seconds from now.
\until asio::steady_timer
In this simple example we perform a blocking wait on the timer.
That is, the call to asio::steady_timer::wait() will not return until the
timer has expired, 5 seconds after it was created (i.e. <b>not</b> from when the
wait starts).
A timer is always in one of two states: "expired" or "not expired". If the
asio::steady_timer::wait() function is called on an expired timer, it will
return immediately.
\until wait
Finally we print the obligatory <tt>"Hello, world!"</tt>
message to show when the timer has expired.
\until }
See the \ref tuttimer1src "full source listing" \n
Return to the \ref index "tutorial index" \n
Next: \ref tuttimer2
*/
/**
\page tuttimer1src Source listing for Timer.1
\include timer1/timer.cpp
Return to \ref tuttimer1
*/
/**
\page tuttimer2 Timer.2 - Using a timer asynchronously
This tutorial program demonstrates how to use asio's asynchronous functionality
by modifying the program from tutorial Timer.1 to perform an asynchronous wait
on the timer.
\dontinclude timer2/timer.cpp
\skip #include
\until asio.hpp
Using asio's asynchronous functionality means supplying a @ref completion_token,
which determines how the result will be delivered to a <em>completion
handler</em> when an @ref asynchronous_operation completes. In this program we
define a function called <tt>print</tt> to be called when the asynchronous wait
finishes.
\until asio::steady_timer
Next, instead of doing a blocking wait as in tutorial Timer.1,
we call the asio::steady_timer::async_wait() function to perform an
asynchronous wait. When calling this function we pass the <tt>print</tt>
function that was defined above.
\skipline async_wait
Finally, we must call the asio::io_context::run() member function
on the io_context object.
The asio library provides a guarantee that completion handlers will <b>only</b>
be called from threads that are currently calling asio::io_context::run().
Therefore unless the asio::io_context::run() function is called the completion
handler for the asynchronous wait completion will never be invoked.
The asio::io_context::run() function will also continue to run while there is
still "work" to do. In this example, the work is the asynchronous wait on the
timer, so the call will not return until the timer has expired and the
completion handler has returned.
It is important to remember to give the io_context some work to do before
calling asio::io_context::run(). For example, if we had omitted the above call
to asio::steady_timer::async_wait(), the io_context would not have had any
work to do, and consequently asio::io_context::run() would have returned
immediately.
\skip run
\until }
See the \ref tuttimer2src "full source listing" \n
Return to the \ref index "tutorial index" \n
Previous: \ref tuttimer1 \n
Next: \ref tuttimer3
*/
/**
\page tuttimer2src Source listing for Timer.2
\include timer2/timer.cpp
Return to \ref tuttimer2
*/
/**
\page tuttimer3 Timer.3 - Binding arguments to a completion handler
In this tutorial we will modify the program from tutorial Timer.2 so that the
timer fires once a second. This will show how to pass additional parameters to
your handler function.
\dontinclude timer3/timer.cpp
\skip #include
\until asio.hpp
To implement a repeating timer using asio you need to change
the timer's expiry time in your completion handler, and to then start a new
asynchronous wait. Obviously this means that the completion handler will need
to be able to access the timer object. To this end we add two new parameters
to the <tt>print</tt> function:
\li a pointer to a timer object; and
\li a counter so that we can stop the program when the timer fires for the
sixth time
at the end of the parameter list.
\until {
As mentioned above, this tutorial program uses a counter to
stop running when the timer fires for the sixth time. However you will observe
that there is no explicit call to ask the io_context to stop. Recall that in
tutorial Timer.2 we learnt that the asio::io_context::run() function completes
when there is no more "work" to do. By not starting a new asynchronous wait on
the timer when <tt>count</tt> reaches 5, the io_context will run out of work and
stop running.
\until ++
Next we move the expiry time for the timer along by one second
from the previous expiry time. By calculating the new expiry time relative to
the old, we can ensure that the timer does not drift away from the
whole-second mark due to any delays in processing the handler.
\until expires_at
Then we start a new asynchronous wait on the timer. As you can
see, the @c std::bind function is used to associate the extra parameters
with your completion handler. The asio::steady_timer::async_wait() function
expects a handler function (or function object) with the signature
<tt>void(const std::error_code&)</tt>. Binding the additional parameters
converts your <tt>print</tt> function into a function object that matches the
signature correctly.
In this example, the asio::placeholders::error argument to @c std::bind is a
named placeholder for the error object passed to the handler. When initiating
the asynchronous operation, and if using @c std::bind, you must specify only
the arguments that match the handler's parameter list. In tutorial Timer.4 you
will see that this placeholder may be elided if the parameter is not needed by
the completion handler.
\until asio::io_context
A new <tt>count</tt> variable is added so that we can stop the
program when the timer fires for the sixth time.
\until asio::steady_timer
As in Step 4, when making the call to
asio::steady_timer::async_wait() from <tt>main</tt> we bind the additional
parameters needed for the <tt>print</tt> function.
\until run
Finally, just to prove that the <tt>count</tt> variable was
being used in the <tt>print</tt> handler function, we will print out its new
value.
\until }
See the \ref tuttimer3src "full source listing" \n
Return to the \ref index "tutorial index" \n
Previous: \ref tuttimer2 \n
Next: \ref tuttimer4
*/
/**
\page tuttimer3src Source listing for Timer.3
\include timer3/timer.cpp
Return to \ref tuttimer3
*/
/**
\page tuttimer4 Timer.4 - Using a member function as a completion handler
In this tutorial we will see how to use a class member function as a completion
handler. The program should execute identically to the tutorial program from
tutorial Timer.3.
\dontinclude timer4/timer.cpp
\skip #include
\until asio.hpp
Instead of defining a free function <tt>print</tt> as the
completion handler, as we did in the earlier tutorial programs, we now define a
class called <tt>printer</tt>.
\until public
The constructor of this class will take a reference to the
io_context object and use it when initialising the <tt>timer_</tt> member. The
counter used to shut down the program is now also a member of the class.
\until {
The @c std::bind function works just as well with class
member functions as with free functions. Since all non-static class member
functions have an implicit <tt>this</tt> parameter, we need to bind
<tt>this</tt> to the function. As in tutorial Timer.3, @c std::bind
converts our completion handler (now a member function) into a function object
that can be invoked as though it has the signature <tt>void(const
std::error_code&)</tt>.
You will note that the asio::placeholders::error placeholder is not specified
here, as the <tt>print</tt> member function does not accept an error object as
a parameter.
\until }
In the class destructor we will print out the final value of
the counter.
\until }
The <tt>print</tt> member function is very similar to the
<tt>print</tt> function from tutorial Timer.3, except that it now operates on
the class data members instead of having the timer and counter passed in as
parameters.
\until };
The <tt>main</tt> function is much simpler than before, as it
now declares a local <tt>printer</tt> object before running the io_context as
normal.
\until }
See the \ref tuttimer4src "full source listing" \n
Return to the \ref index "tutorial index" \n
Previous: \ref tuttimer3 \n
Next: \ref tuttimer5 \n
*/
/**
\page tuttimer4src Source listing for Timer.4
\include timer4/timer.cpp
Return to \ref tuttimer4
*/
/**
\page tuttimer5 Timer.5 - Synchronising completion handlers in multithreaded programs
This tutorial demonstrates the use of the asio::strand class template to
synchronise completion handlers in a multithreaded program.
The previous four tutorials avoided the issue of handler synchronisation by
calling the asio::io_context::run() function from one thread only. As you
already know, the asio library provides a guarantee that completion handlers
will <b>only</b> be called from threads that are currently calling
asio::io_context::run(). Consequently, calling asio::io_context::run() from
only one thread ensures that completion handlers cannot run concurrently.
The single threaded approach is usually the best place to start when
developing applications using asio. The downside is the limitations it places
on programs, particularly servers, including:
<ul>
<li>Poor responsiveness when handlers can take a long time to complete.</li>
<li>An inability to scale on multiprocessor systems.</li>
</ul>
If you find yourself running into these limitations, an alternative approach
is to have a pool of threads calling asio::io_context::run(). However, as this
allows handlers to execute concurrently, we need a method of synchronisation
when handlers might be accessing a shared, thread-unsafe resource.
\dontinclude timer5/timer.cpp
\skip #include
\until asio.hpp
We start by defining a class called <tt>printer</tt>, similar
to the class in the previous tutorial. This class will extend the previous
tutorial by running two timers in parallel.
\until public
In addition to initialising a pair of asio::steady_timer members, the
constructor initialises the <tt>strand_</tt> member, an object of type
asio::strand<asio::io_context::executor_type>.
The asio::strand class template is an executor adapter that guarantees
that, for those handlers that are dispatched through it, an executing handler
will be allowed to complete before the next one is started. This is guaranteed
irrespective of the number of threads that are calling
asio::io_context::run(). Of course, the handlers may still execute
concurrently with other handlers that were <b>not</b> dispatched through an
asio::strand, or were dispatched through a different asio::strand
object.
\until {
When initiating the asynchronous operations, each completion handler is "bound"
to an asio::strand<asio::io_context::executor_type> object. The
asio::bind_executor() function returns a new handler that automatically
dispatches its contained handler through the asio::strand object. By
binding the handlers to the same asio::strand, we are ensuring that they
cannot execute concurrently.
\until }
\until }
In a multithreaded program, the handlers for asynchronous
operations should be synchronised if they access shared resources. In this
tutorial, the shared resources used by the handlers (<tt>print1</tt> and
<tt>print2</tt>) are <tt>std::cout</tt> and the <tt>count_</tt> data member.
\until };
The <tt>main</tt> function now causes asio::io_context::run() to
be called from two threads: the main thread and one additional thread. This is
accomplished using an asio::thread object.
Just as it would with a call from a single thread, concurrent calls to
asio::io_context::run() will continue to execute while there is "work" left to
do. The background thread will not exit until all asynchronous operations have
completed.
\until }
See the \ref tuttimer5src "full source listing" \n
Return to the \ref index "tutorial index" \n
Previous: \ref tuttimer4 \n
*/
/**
\page tuttimer5src Source listing for Timer.5
\include timer5/timer.cpp
Return to \ref tuttimer5
*/
|
0 | repos/asio/asio/src/examples/cpp11/tutorial | repos/asio/asio/src/examples/cpp11/tutorial/daytime5/server.cpp | //
// server.cpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <array>
#include <ctime>
#include <iostream>
#include <string>
#include <asio.hpp>
using asio::ip::udp;
std::string make_daytime_string()
{
using namespace std; // For time_t, time and ctime;
time_t now = time(0);
return ctime(&now);
}
int main()
{
try
{
asio::io_context io_context;
udp::socket socket(io_context, udp::endpoint(udp::v4(), 13));
for (;;)
{
std::array<char, 1> recv_buf;
udp::endpoint remote_endpoint;
socket.receive_from(asio::buffer(recv_buf), remote_endpoint);
std::string message = make_daytime_string();
std::error_code ignored_error;
socket.send_to(asio::buffer(message),
remote_endpoint, 0, ignored_error);
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11/tutorial | repos/asio/asio/src/examples/cpp11/tutorial/daytime7/server.cpp | //
// server.cpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <array>
#include <ctime>
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include <asio.hpp>
using asio::ip::tcp;
using asio::ip::udp;
std::string make_daytime_string()
{
using namespace std; // For time_t, time and ctime;
time_t now = time(0);
return ctime(&now);
}
class tcp_connection
: public std::enable_shared_from_this<tcp_connection>
{
public:
typedef std::shared_ptr<tcp_connection> pointer;
static pointer create(asio::io_context& io_context)
{
return pointer(new tcp_connection(io_context));
}
tcp::socket& socket()
{
return socket_;
}
void start()
{
message_ = make_daytime_string();
asio::async_write(socket_, asio::buffer(message_),
std::bind(&tcp_connection::handle_write, shared_from_this()));
}
private:
tcp_connection(asio::io_context& io_context)
: socket_(io_context)
{
}
void handle_write()
{
}
tcp::socket socket_;
std::string message_;
};
class tcp_server
{
public:
tcp_server(asio::io_context& io_context)
: io_context_(io_context),
acceptor_(io_context, tcp::endpoint(tcp::v4(), 13))
{
start_accept();
}
private:
void start_accept()
{
tcp_connection::pointer new_connection =
tcp_connection::create(io_context_);
acceptor_.async_accept(new_connection->socket(),
std::bind(&tcp_server::handle_accept, this, new_connection,
asio::placeholders::error));
}
void handle_accept(tcp_connection::pointer new_connection,
const std::error_code& error)
{
if (!error)
{
new_connection->start();
}
start_accept();
}
asio::io_context& io_context_;
tcp::acceptor acceptor_;
};
class udp_server
{
public:
udp_server(asio::io_context& io_context)
: socket_(io_context, udp::endpoint(udp::v4(), 13))
{
start_receive();
}
private:
void start_receive()
{
socket_.async_receive_from(
asio::buffer(recv_buffer_), remote_endpoint_,
std::bind(&udp_server::handle_receive, this,
asio::placeholders::error));
}
void handle_receive(const std::error_code& error)
{
if (!error)
{
std::shared_ptr<std::string> message(
new std::string(make_daytime_string()));
socket_.async_send_to(asio::buffer(*message), remote_endpoint_,
std::bind(&udp_server::handle_send, this, message));
start_receive();
}
}
void handle_send(std::shared_ptr<std::string> /*message*/)
{
}
udp::socket socket_;
udp::endpoint remote_endpoint_;
std::array<char, 1> recv_buffer_;
};
int main()
{
try
{
asio::io_context io_context;
tcp_server server1(io_context);
udp_server server2(io_context);
io_context.run();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11/tutorial | repos/asio/asio/src/examples/cpp11/tutorial/daytime6/server.cpp | //
// server.cpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <array>
#include <ctime>
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include <asio.hpp>
using asio::ip::udp;
std::string make_daytime_string()
{
using namespace std; // For time_t, time and ctime;
time_t now = time(0);
return ctime(&now);
}
class udp_server
{
public:
udp_server(asio::io_context& io_context)
: socket_(io_context, udp::endpoint(udp::v4(), 13))
{
start_receive();
}
private:
void start_receive()
{
socket_.async_receive_from(
asio::buffer(recv_buffer_), remote_endpoint_,
std::bind(&udp_server::handle_receive, this,
asio::placeholders::error,
asio::placeholders::bytes_transferred));
}
void handle_receive(const std::error_code& error,
std::size_t /*bytes_transferred*/)
{
if (!error)
{
std::shared_ptr<std::string> message(
new std::string(make_daytime_string()));
socket_.async_send_to(asio::buffer(*message), remote_endpoint_,
std::bind(&udp_server::handle_send, this, message,
asio::placeholders::error,
asio::placeholders::bytes_transferred));
start_receive();
}
}
void handle_send(std::shared_ptr<std::string> /*message*/,
const std::error_code& /*error*/,
std::size_t /*bytes_transferred*/)
{
}
udp::socket socket_;
udp::endpoint remote_endpoint_;
std::array<char, 1> recv_buffer_;
};
int main()
{
try
{
asio::io_context io_context;
udp_server server(io_context);
io_context.run();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11/tutorial | repos/asio/asio/src/examples/cpp11/tutorial/timer5/timer.cpp | //
// timer.cpp
// ~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <functional>
#include <iostream>
#include <thread>
#include <asio.hpp>
class printer
{
public:
printer(asio::io_context& io)
: strand_(asio::make_strand(io)),
timer1_(io, asio::chrono::seconds(1)),
timer2_(io, asio::chrono::seconds(1)),
count_(0)
{
timer1_.async_wait(asio::bind_executor(strand_,
std::bind(&printer::print1, this)));
timer2_.async_wait(asio::bind_executor(strand_,
std::bind(&printer::print2, this)));
}
~printer()
{
std::cout << "Final count is " << count_ << std::endl;
}
void print1()
{
if (count_ < 10)
{
std::cout << "Timer 1: " << count_ << std::endl;
++count_;
timer1_.expires_at(timer1_.expiry() + asio::chrono::seconds(1));
timer1_.async_wait(asio::bind_executor(strand_,
std::bind(&printer::print1, this)));
}
}
void print2()
{
if (count_ < 10)
{
std::cout << "Timer 2: " << count_ << std::endl;
++count_;
timer2_.expires_at(timer2_.expiry() + asio::chrono::seconds(1));
timer2_.async_wait(asio::bind_executor(strand_,
std::bind(&printer::print2, this)));
}
}
private:
asio::strand<asio::io_context::executor_type> strand_;
asio::steady_timer timer1_;
asio::steady_timer timer2_;
int count_;
};
int main()
{
asio::io_context io;
printer p(io);
std::thread t([&]{ io.run(); });
io.run();
t.join();
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11/tutorial | repos/asio/asio/src/examples/cpp11/tutorial/timer4/timer.cpp | //
// timer.cpp
// ~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <functional>
#include <iostream>
#include <asio.hpp>
class printer
{
public:
printer(asio::io_context& io)
: timer_(io, asio::chrono::seconds(1)),
count_(0)
{
timer_.async_wait(std::bind(&printer::print, this));
}
~printer()
{
std::cout << "Final count is " << count_ << std::endl;
}
void print()
{
if (count_ < 5)
{
std::cout << count_ << std::endl;
++count_;
timer_.expires_at(timer_.expiry() + asio::chrono::seconds(1));
timer_.async_wait(std::bind(&printer::print, this));
}
}
private:
asio::steady_timer timer_;
int count_;
};
int main()
{
asio::io_context io;
printer p(io);
io.run();
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11/tutorial | repos/asio/asio/src/examples/cpp11/tutorial/timer1/timer.cpp | //
// timer.cpp
// ~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <iostream>
#include <asio.hpp>
int main()
{
asio::io_context io;
asio::steady_timer t(io, asio::chrono::seconds(5));
t.wait();
std::cout << "Hello, world!" << std::endl;
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11/tutorial | repos/asio/asio/src/examples/cpp11/tutorial/daytime4/client.cpp | //
// client.cpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <array>
#include <iostream>
#include <asio.hpp>
using asio::ip::udp;
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: client <host>" << std::endl;
return 1;
}
asio::io_context io_context;
udp::resolver resolver(io_context);
udp::endpoint receiver_endpoint =
*resolver.resolve(udp::v4(), argv[1], "daytime").begin();
udp::socket socket(io_context);
socket.open(udp::v4());
std::array<char, 1> send_buf = {{ 0 }};
socket.send_to(asio::buffer(send_buf), receiver_endpoint);
std::array<char, 128> recv_buf;
udp::endpoint sender_endpoint;
size_t len = socket.receive_from(
asio::buffer(recv_buf), sender_endpoint);
std::cout.write(recv_buf.data(), len);
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11/tutorial | repos/asio/asio/src/examples/cpp11/tutorial/timer2/timer.cpp | //
// timer.cpp
// ~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <iostream>
#include <asio.hpp>
void print(const std::error_code& /*e*/)
{
std::cout << "Hello, world!" << std::endl;
}
int main()
{
asio::io_context io;
asio::steady_timer t(io, asio::chrono::seconds(5));
t.async_wait(&print);
io.run();
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11/tutorial | repos/asio/asio/src/examples/cpp11/tutorial/daytime3/server.cpp | //
// server.cpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <ctime>
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include <asio.hpp>
using asio::ip::tcp;
std::string make_daytime_string()
{
using namespace std; // For time_t, time and ctime;
time_t now = time(0);
return ctime(&now);
}
class tcp_connection
: public std::enable_shared_from_this<tcp_connection>
{
public:
typedef std::shared_ptr<tcp_connection> pointer;
static pointer create(asio::io_context& io_context)
{
return pointer(new tcp_connection(io_context));
}
tcp::socket& socket()
{
return socket_;
}
void start()
{
message_ = make_daytime_string();
asio::async_write(socket_, asio::buffer(message_),
std::bind(&tcp_connection::handle_write, shared_from_this(),
asio::placeholders::error,
asio::placeholders::bytes_transferred));
}
private:
tcp_connection(asio::io_context& io_context)
: socket_(io_context)
{
}
void handle_write(const std::error_code& /*error*/,
size_t /*bytes_transferred*/)
{
}
tcp::socket socket_;
std::string message_;
};
class tcp_server
{
public:
tcp_server(asio::io_context& io_context)
: io_context_(io_context),
acceptor_(io_context, tcp::endpoint(tcp::v4(), 13))
{
start_accept();
}
private:
void start_accept()
{
tcp_connection::pointer new_connection =
tcp_connection::create(io_context_);
acceptor_.async_accept(new_connection->socket(),
std::bind(&tcp_server::handle_accept, this, new_connection,
asio::placeholders::error));
}
void handle_accept(tcp_connection::pointer new_connection,
const std::error_code& error)
{
if (!error)
{
new_connection->start();
}
start_accept();
}
asio::io_context& io_context_;
tcp::acceptor acceptor_;
};
int main()
{
try
{
asio::io_context io_context;
tcp_server server(io_context);
io_context.run();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11/tutorial | repos/asio/asio/src/examples/cpp11/tutorial/timer3/timer.cpp | //
// timer.cpp
// ~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <functional>
#include <iostream>
#include <asio.hpp>
void print(const std::error_code& /*e*/,
asio::steady_timer* t, int* count)
{
if (*count < 5)
{
std::cout << *count << std::endl;
++(*count);
t->expires_at(t->expiry() + asio::chrono::seconds(1));
t->async_wait(std::bind(print,
asio::placeholders::error, t, count));
}
}
int main()
{
asio::io_context io;
int count = 0;
asio::steady_timer t(io, asio::chrono::seconds(1));
t.async_wait(std::bind(print,
asio::placeholders::error, &t, &count));
io.run();
std::cout << "Final count is " << count << std::endl;
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11/tutorial | repos/asio/asio/src/examples/cpp11/tutorial/daytime1/client.cpp | //
// client.cpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <array>
#include <iostream>
#include <asio.hpp>
using asio::ip::tcp;
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: client <host>" << std::endl;
return 1;
}
asio::io_context io_context;
tcp::resolver resolver(io_context);
tcp::resolver::results_type endpoints =
resolver.resolve(argv[1], "daytime");
tcp::socket socket(io_context);
asio::connect(socket, endpoints);
for (;;)
{
std::array<char, 128> buf;
std::error_code error;
size_t len = socket.read_some(asio::buffer(buf), error);
if (error == asio::error::eof)
break; // Connection closed cleanly by peer.
else if (error)
throw std::system_error(error); // Some other error.
std::cout.write(buf.data(), len);
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11/tutorial | repos/asio/asio/src/examples/cpp11/tutorial/daytime2/server.cpp | //
// server.cpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <ctime>
#include <iostream>
#include <string>
#include <asio.hpp>
using asio::ip::tcp;
std::string make_daytime_string()
{
using namespace std; // For time_t, time and ctime;
time_t now = time(0);
return ctime(&now);
}
int main()
{
try
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), 13));
for (;;)
{
tcp::socket socket(io_context);
acceptor.accept(socket);
std::string message = make_daytime_string();
std::error_code ignored_error;
asio::write(socket, asio::buffer(message), ignored_error);
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp11 | repos/asio/asio/src/examples/cpp11/buffers/reference_counted.cpp | //
// reference_counted.cpp
// ~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio.hpp>
#include <iostream>
#include <memory>
#include <utility>
#include <vector>
#include <ctime>
using asio::ip::tcp;
// A reference-counted non-modifiable buffer class.
class shared_const_buffer
{
public:
// Construct from a std::string.
explicit shared_const_buffer(const std::string& data)
: data_(new std::vector<char>(data.begin(), data.end())),
buffer_(asio::buffer(*data_))
{
}
// Implement the ConstBufferSequence requirements.
typedef asio::const_buffer value_type;
typedef const asio::const_buffer* const_iterator;
const asio::const_buffer* begin() const { return &buffer_; }
const asio::const_buffer* end() const { return &buffer_ + 1; }
private:
std::shared_ptr<std::vector<char> > data_;
asio::const_buffer buffer_;
};
class session
: public std::enable_shared_from_this<session>
{
public:
session(tcp::socket socket)
: socket_(std::move(socket))
{
}
void start()
{
do_write();
}
private:
void do_write()
{
std::time_t now = std::time(0);
shared_const_buffer buffer(std::ctime(&now));
auto self(shared_from_this());
asio::async_write(socket_, buffer,
[self](std::error_code /*ec*/, std::size_t /*length*/)
{
});
}
// The socket used to communicate with the client.
tcp::socket socket_;
};
class server
{
public:
server(asio::io_context& io_context, short port)
: acceptor_(io_context, tcp::endpoint(tcp::v4(), port))
{
do_accept();
}
private:
void do_accept()
{
acceptor_.async_accept(
[this](std::error_code ec, tcp::socket socket)
{
if (!ec)
{
std::make_shared<session>(std::move(socket))->start();
}
do_accept();
});
}
tcp::acceptor acceptor_;
};
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: reference_counted <port>\n";
return 1;
}
asio::io_context io_context;
server s(io_context, std::atoi(argv[1]));
io_context.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp20 | repos/asio/asio/src/examples/cpp20/type_erasure/sleep.hpp | //
// sleep.hpp
// ~~~~~~~~~
//
// Copyright (c) 2003-2024 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)
//
#ifndef SLEEP_HPP
#define SLEEP_HPP
#include <asio/any_completion_handler.hpp>
#include <asio/any_io_executor.hpp>
#include <asio/async_result.hpp>
#include <asio/error.hpp>
#include <chrono>
void async_sleep_impl(
asio::any_completion_handler<void(std::error_code)> handler,
asio::any_io_executor ex, std::chrono::nanoseconds duration);
template <typename CompletionToken>
inline auto async_sleep(asio::any_io_executor ex,
std::chrono::nanoseconds duration, CompletionToken&& token)
{
return asio::async_initiate<CompletionToken, void(std::error_code)>(
async_sleep_impl, token, std::move(ex), duration);
}
#endif // SLEEP_HPP
|
0 | repos/asio/asio/src/examples/cpp20 | repos/asio/asio/src/examples/cpp20/type_erasure/line_reader.hpp | //
// line_reader.hpp
// ~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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)
//
#ifndef LINE_READER_HPP
#define LINE_READER_HPP
#include <asio/any_completion_handler.hpp>
#include <asio/async_result.hpp>
#include <asio/error.hpp>
#include <string>
class line_reader
{
public:
virtual ~line_reader() {}
template <typename CompletionToken>
auto async_read_line(std::string prompt, CompletionToken&& token)
{
return asio::async_initiate<CompletionToken, void(asio::error_code, std::string)>(
[](auto handler, line_reader* self, std::string prompt)
{
self->async_read_line_impl(std::move(prompt), std::move(handler));
}, token, this, prompt);
}
private:
virtual void async_read_line_impl(std::string prompt,
asio::any_completion_handler<void(asio::error_code, std::string)> handler) = 0;
};
#endif // LINE_READER_HPP
|
0 | repos/asio/asio/src/examples/cpp20 | repos/asio/asio/src/examples/cpp20/type_erasure/stdin_line_reader.hpp | //
// stdin_line_reader.hpp
// ~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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)
//
#ifndef STDIN_LINE_READER_HPP
#define STDIN_LINE_READER_HPP
#include "line_reader.hpp"
#include <asio/posix/stream_descriptor.hpp>
class stdin_line_reader : public line_reader
{
public:
explicit stdin_line_reader(asio::any_io_executor ex);
private:
void async_read_line_impl(std::string prompt,
asio::any_completion_handler<void(asio::error_code, std::string)> handler) override;
asio::posix::stream_descriptor stdin_;
std::string buffer_;
};
#endif
|
0 | repos/asio/asio/src/examples/cpp20 | repos/asio/asio/src/examples/cpp20/type_erasure/stdin_line_reader.cpp | //
// stdin_line_reader.cpp
// ~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 "stdin_line_reader.hpp"
#include <asio/deferred.hpp>
#include <asio/read_until.hpp>
#include <iostream>
stdin_line_reader::stdin_line_reader(asio::any_io_executor ex)
: stdin_(ex, ::dup(STDIN_FILENO))
{
}
void stdin_line_reader::async_read_line_impl(std::string prompt,
asio::any_completion_handler<void(asio::error_code, std::string)> handler)
{
std::cout << prompt;
std::cout.flush();
asio::async_read_until(stdin_, asio::dynamic_buffer(buffer_), '\n',
asio::deferred(
[this](asio::error_code ec, std::size_t n)
{
if (!ec)
{
std::string result = buffer_.substr(0, n);
buffer_.erase(0, n);
return asio::deferred.values(ec, std::move(result));
}
else
{
return asio::deferred.values(ec, std::string{});
}
}
)
)(std::move(handler));
}
|
0 | repos/asio/asio/src/examples/cpp20 | repos/asio/asio/src/examples/cpp20/type_erasure/sleep.cpp | //
// sleep.cpp
// ~~~~~~~~~
//
// Copyright (c) 2003-2024 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 "sleep.hpp"
#include <asio/consign.hpp>
#include <asio/steady_timer.hpp>
#include <memory>
void async_sleep_impl(
asio::any_completion_handler<void(std::error_code)> handler,
asio::any_io_executor ex, std::chrono::nanoseconds duration)
{
auto timer = std::make_shared<asio::steady_timer>(ex, duration);
timer->async_wait(asio::consign(std::move(handler), timer));
}
|
0 | repos/asio/asio/src/examples/cpp20 | repos/asio/asio/src/examples/cpp20/type_erasure/main.cpp | //
// main.cpp
// ~~~~~~~~
//
// Copyright (c) 2003-2024 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 "line_reader.hpp"
#include "sleep.hpp"
#include "stdin_line_reader.hpp"
#include <asio/co_spawn.hpp>
#include <asio/detached.hpp>
#include <asio/io_context.hpp>
#include <asio/use_awaitable.hpp>
#include <iostream>
asio::awaitable<void> do_read(line_reader& reader)
{
for (int i = 0; i < 10; ++i)
{
std::cout << co_await reader.async_read_line("Enter something: ", asio::use_awaitable);
co_await async_sleep(co_await asio::this_coro::executor, std::chrono::seconds(1), asio::use_awaitable);
}
}
int main()
{
asio::io_context ctx{1};
stdin_line_reader reader{ctx.get_executor()};
co_spawn(ctx, do_read(reader), asio::detached);
ctx.run();
}
|
0 | repos/asio/asio/src/examples/cpp20 | repos/asio/asio/src/examples/cpp20/coroutines/echo_server_with_as_tuple_default.cpp | //
// echo_server_with_as_tuple_default.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio/as_tuple.hpp>
#include <asio/co_spawn.hpp>
#include <asio/detached.hpp>
#include <asio/io_context.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/signal_set.hpp>
#include <asio/write.hpp>
#include <cstdio>
using asio::as_tuple_t;
using asio::ip::tcp;
using asio::awaitable;
using asio::co_spawn;
using asio::detached;
using asio::use_awaitable_t;
using default_token = as_tuple_t<use_awaitable_t<>>;
using tcp_acceptor = default_token::as_default_on_t<tcp::acceptor>;
using tcp_socket = default_token::as_default_on_t<tcp::socket>;
namespace this_coro = asio::this_coro;
awaitable<void> echo(tcp_socket socket)
{
char data[1024];
for (;;)
{
auto [e1, nread] = co_await socket.async_read_some(asio::buffer(data));
if (nread == 0) break;
auto [e2, nwritten] = co_await async_write(socket, asio::buffer(data, nread));
if (nwritten != nread) break;
}
}
awaitable<void> listener()
{
auto executor = co_await this_coro::executor;
tcp_acceptor acceptor(executor, {tcp::v4(), 55555});
for (;;)
{
if (auto [e, socket] = co_await acceptor.async_accept(); socket.is_open())
co_spawn(executor, echo(std::move(socket)), detached);
}
}
int main()
{
try
{
asio::io_context io_context(1);
asio::signal_set signals(io_context, SIGINT, SIGTERM);
signals.async_wait([&](auto, auto){ io_context.stop(); });
co_spawn(io_context, listener(), detached);
io_context.run();
}
catch (std::exception& e)
{
std::printf("Exception: %s\n", e.what());
}
}
|
0 | repos/asio/asio/src/examples/cpp20 | repos/asio/asio/src/examples/cpp20/coroutines/echo_server_with_as_single_default.cpp | //
// echo_server_with_as_single_default.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio/experimental/as_single.hpp>
#include <asio/co_spawn.hpp>
#include <asio/detached.hpp>
#include <asio/io_context.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/signal_set.hpp>
#include <asio/write.hpp>
#include <cstdio>
using asio::experimental::as_single_t;
using asio::ip::tcp;
using asio::awaitable;
using asio::co_spawn;
using asio::detached;
using asio::use_awaitable_t;
using default_token = as_single_t<use_awaitable_t<>>;
using tcp_acceptor = default_token::as_default_on_t<tcp::acceptor>;
using tcp_socket = default_token::as_default_on_t<tcp::socket>;
namespace this_coro = asio::this_coro;
awaitable<void> echo(tcp_socket socket)
{
char data[1024];
for (;;)
{
auto [e1, nread] = co_await socket.async_read_some(asio::buffer(data));
if (nread == 0) break;
auto [e2, nwritten] = co_await async_write(socket, asio::buffer(data, nread));
if (nwritten != nread) break;
}
}
awaitable<void> listener()
{
auto executor = co_await this_coro::executor;
tcp_acceptor acceptor(executor, {tcp::v4(), 55555});
for (;;)
{
if (auto [e, socket] = co_await acceptor.async_accept(); socket.is_open())
co_spawn(executor, echo(std::move(socket)), detached);
}
}
int main()
{
try
{
asio::io_context io_context(1);
asio::signal_set signals(io_context, SIGINT, SIGTERM);
signals.async_wait([&](auto, auto){ io_context.stop(); });
co_spawn(io_context, listener(), detached);
io_context.run();
}
catch (std::exception& e)
{
std::printf("Exception: %s\n", e.what());
}
}
|
0 | repos/asio/asio/src/examples/cpp20 | repos/asio/asio/src/examples/cpp20/coroutines/echo_server_with_deferred_default.cpp | //
// echo_server.cpp
// ~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio/co_spawn.hpp>
#include <asio/deferred.hpp>
#include <asio/detached.hpp>
#include <asio/io_context.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/signal_set.hpp>
#include <asio/write.hpp>
#include <cstdio>
using asio::ip::tcp;
using asio::awaitable;
using asio::co_spawn;
using asio::detached;
namespace this_coro = asio::this_coro;
awaitable<void> echo(tcp::socket socket)
{
try
{
char data[1024];
for (;;)
{
std::size_t n = co_await socket.async_read_some(asio::buffer(data));
co_await async_write(socket, asio::buffer(data, n));
}
}
catch (std::exception& e)
{
std::printf("echo Exception: %s\n", e.what());
}
}
awaitable<void> listener()
{
auto executor = co_await this_coro::executor;
tcp::acceptor acceptor(executor, {tcp::v4(), 55555});
for (;;)
{
tcp::socket socket = co_await acceptor.async_accept();
co_spawn(executor, echo(std::move(socket)), detached);
}
}
int main()
{
try
{
asio::io_context io_context(1);
asio::signal_set signals(io_context, SIGINT, SIGTERM);
signals.async_wait([&](auto, auto){ io_context.stop(); });
co_spawn(io_context, listener(), detached);
io_context.run();
}
catch (std::exception& e)
{
std::printf("Exception: %s\n", e.what());
}
}
|
0 | repos/asio/asio/src/examples/cpp20 | repos/asio/asio/src/examples/cpp20/coroutines/echo_server_with_deferred.cpp | //
// echo_server.cpp
// ~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio/co_spawn.hpp>
#include <asio/deferred.hpp>
#include <asio/detached.hpp>
#include <asio/io_context.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/signal_set.hpp>
#include <asio/write.hpp>
#include <cstdio>
using asio::ip::tcp;
using asio::awaitable;
using asio::co_spawn;
using asio::deferred;
using asio::detached;
namespace this_coro = asio::this_coro;
awaitable<void> echo(tcp::socket socket)
{
try
{
char data[1024];
for (;;)
{
std::size_t n = co_await socket.async_read_some(asio::buffer(data), deferred);
co_await async_write(socket, asio::buffer(data, n), deferred);
}
}
catch (std::exception& e)
{
std::printf("echo Exception: %s\n", e.what());
}
}
awaitable<void> listener()
{
auto executor = co_await this_coro::executor;
tcp::acceptor acceptor(executor, {tcp::v4(), 55555});
for (;;)
{
tcp::socket socket = co_await acceptor.async_accept(deferred);
co_spawn(executor, echo(std::move(socket)), detached);
}
}
int main()
{
try
{
asio::io_context io_context(1);
asio::signal_set signals(io_context, SIGINT, SIGTERM);
signals.async_wait([&](auto, auto){ io_context.stop(); });
co_spawn(io_context, listener(), detached);
io_context.run();
}
catch (std::exception& e)
{
std::printf("Exception: %s\n", e.what());
}
}
|
0 | repos/asio/asio/src/examples/cpp20 | repos/asio/asio/src/examples/cpp20/coroutines/echo_server.cpp | //
// echo_server.cpp
// ~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio/co_spawn.hpp>
#include <asio/detached.hpp>
#include <asio/io_context.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/signal_set.hpp>
#include <asio/write.hpp>
#include <cstdio>
using asio::ip::tcp;
using asio::awaitable;
using asio::co_spawn;
using asio::detached;
using asio::use_awaitable;
namespace this_coro = asio::this_coro;
#if defined(ASIO_ENABLE_HANDLER_TRACKING)
# define use_awaitable \
asio::use_awaitable_t(__FILE__, __LINE__, __PRETTY_FUNCTION__)
#endif
awaitable<void> echo(tcp::socket socket)
{
try
{
char data[1024];
for (;;)
{
std::size_t n = co_await socket.async_read_some(asio::buffer(data), use_awaitable);
co_await async_write(socket, asio::buffer(data, n), use_awaitable);
}
}
catch (std::exception& e)
{
std::printf("echo Exception: %s\n", e.what());
}
}
awaitable<void> listener()
{
auto executor = co_await this_coro::executor;
tcp::acceptor acceptor(executor, {tcp::v4(), 55555});
for (;;)
{
tcp::socket socket = co_await acceptor.async_accept(use_awaitable);
co_spawn(executor, echo(std::move(socket)), detached);
}
}
int main()
{
try
{
asio::io_context io_context(1);
asio::signal_set signals(io_context, SIGINT, SIGTERM);
signals.async_wait([&](auto, auto){ io_context.stop(); });
co_spawn(io_context, listener(), detached);
io_context.run();
}
catch (std::exception& e)
{
std::printf("Exception: %s\n", e.what());
}
}
|
0 | repos/asio/asio/src/examples/cpp20 | repos/asio/asio/src/examples/cpp20/coroutines/echo_server_with_default.cpp | //
// echo_server_with_default.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio/co_spawn.hpp>
#include <asio/detached.hpp>
#include <asio/io_context.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/signal_set.hpp>
#include <asio/write.hpp>
#include <cstdio>
using asio::ip::tcp;
using asio::awaitable;
using asio::co_spawn;
using asio::detached;
using asio::use_awaitable_t;
using tcp_acceptor = use_awaitable_t<>::as_default_on_t<tcp::acceptor>;
using tcp_socket = use_awaitable_t<>::as_default_on_t<tcp::socket>;
namespace this_coro = asio::this_coro;
awaitable<void> echo(tcp_socket socket)
{
try
{
char data[1024];
for (;;)
{
std::size_t n = co_await socket.async_read_some(asio::buffer(data));
co_await async_write(socket, asio::buffer(data, n));
}
}
catch (std::exception& e)
{
std::printf("echo Exception: %s\n", e.what());
}
}
awaitable<void> listener()
{
auto executor = co_await this_coro::executor;
tcp_acceptor acceptor(executor, {tcp::v4(), 55555});
for (;;)
{
auto socket = co_await acceptor.async_accept();
co_spawn(executor, echo(std::move(socket)), detached);
}
}
int main()
{
try
{
asio::io_context io_context(1);
asio::signal_set signals(io_context, SIGINT, SIGTERM);
signals.async_wait([&](auto, auto){ io_context.stop(); });
co_spawn(io_context, listener(), detached);
io_context.run();
}
catch (std::exception& e)
{
std::printf("Exception: %s\n", e.what());
}
}
|
0 | repos/asio/asio/src/examples/cpp20 | repos/asio/asio/src/examples/cpp20/coroutines/refactored_echo_server.cpp | //
// refactored_echo_server.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio/co_spawn.hpp>
#include <asio/detached.hpp>
#include <asio/io_context.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/signal_set.hpp>
#include <asio/write.hpp>
#include <cstdio>
using asio::ip::tcp;
using asio::awaitable;
using asio::co_spawn;
using asio::detached;
using asio::use_awaitable;
namespace this_coro = asio::this_coro;
awaitable<void> echo_once(tcp::socket& socket)
{
char data[128];
std::size_t n = co_await socket.async_read_some(asio::buffer(data), use_awaitable);
co_await async_write(socket, asio::buffer(data, n), use_awaitable);
}
awaitable<void> echo(tcp::socket socket)
{
try
{
for (;;)
{
// The asynchronous operations to echo a single chunk of data have been
// refactored into a separate function. When this function is called, the
// operations are still performed in the context of the current
// coroutine, and the behaviour is functionally equivalent.
co_await echo_once(socket);
}
}
catch (std::exception& e)
{
std::printf("echo Exception: %s\n", e.what());
}
}
awaitable<void> listener()
{
auto executor = co_await this_coro::executor;
tcp::acceptor acceptor(executor, {tcp::v4(), 55555});
for (;;)
{
tcp::socket socket = co_await acceptor.async_accept(use_awaitable);
co_spawn(executor, echo(std::move(socket)), detached);
}
}
int main()
{
try
{
asio::io_context io_context(1);
asio::signal_set signals(io_context, SIGINT, SIGTERM);
signals.async_wait([&](auto, auto){ io_context.stop(); });
co_spawn(io_context, listener(), detached);
io_context.run();
}
catch (std::exception& e)
{
std::printf("Exception: %s\n", e.what());
}
}
|
0 | repos/asio/asio/src/examples/cpp20 | repos/asio/asio/src/examples/cpp20/coroutines/timeout.cpp | //
// timeout.cpp
// ~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <asio.hpp>
#include <asio/experimental/awaitable_operators.hpp>
using namespace asio;
using namespace asio::experimental::awaitable_operators;
using time_point = std::chrono::steady_clock::time_point;
using ip::tcp;
awaitable<void> echo(tcp::socket& sock, time_point& deadline)
{
char data[4196];
for (;;)
{
deadline = std::chrono::steady_clock::now() + std::chrono::seconds(10);
auto n = co_await sock.async_read_some(buffer(data), use_awaitable);
co_await async_write(sock, buffer(data, n), use_awaitable);
}
}
awaitable<void> watchdog(time_point& deadline)
{
steady_timer timer(co_await this_coro::executor);
auto now = std::chrono::steady_clock::now();
while (deadline > now)
{
timer.expires_at(deadline);
co_await timer.async_wait(use_awaitable);
now = std::chrono::steady_clock::now();
}
throw std::system_error(std::make_error_code(std::errc::timed_out));
}
awaitable<void> handle_connection(tcp::socket sock)
{
time_point deadline{};
co_await (echo(sock, deadline) && watchdog(deadline));
}
awaitable<void> listen(tcp::acceptor& acceptor)
{
for (;;)
{
co_spawn(
acceptor.get_executor(),
handle_connection(co_await acceptor.async_accept(use_awaitable)),
detached);
}
}
int main()
{
io_context ctx;
tcp::acceptor acceptor(ctx, {tcp::v4(), 54321});
co_spawn(ctx, listen(acceptor), detached);
ctx.run();
}
|
0 | repos/asio/asio/src/examples/cpp20 | repos/asio/asio/src/examples/cpp20/coroutines/chat_server.cpp | //
// chat_server.cpp
// ~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 <cstdlib>
#include <deque>
#include <iostream>
#include <list>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <asio/awaitable.hpp>
#include <asio/detached.hpp>
#include <asio/co_spawn.hpp>
#include <asio/io_context.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/read_until.hpp>
#include <asio/redirect_error.hpp>
#include <asio/signal_set.hpp>
#include <asio/steady_timer.hpp>
#include <asio/use_awaitable.hpp>
#include <asio/write.hpp>
using asio::ip::tcp;
using asio::awaitable;
using asio::co_spawn;
using asio::detached;
using asio::redirect_error;
using asio::use_awaitable;
//----------------------------------------------------------------------
class chat_participant
{
public:
virtual ~chat_participant() {}
virtual void deliver(const std::string& msg) = 0;
};
typedef std::shared_ptr<chat_participant> chat_participant_ptr;
//----------------------------------------------------------------------
class chat_room
{
public:
void join(chat_participant_ptr participant)
{
participants_.insert(participant);
for (auto msg: recent_msgs_)
participant->deliver(msg);
}
void leave(chat_participant_ptr participant)
{
participants_.erase(participant);
}
void deliver(const std::string& msg)
{
recent_msgs_.push_back(msg);
while (recent_msgs_.size() > max_recent_msgs)
recent_msgs_.pop_front();
for (auto participant: participants_)
participant->deliver(msg);
}
private:
std::set<chat_participant_ptr> participants_;
enum { max_recent_msgs = 100 };
std::deque<std::string> recent_msgs_;
};
//----------------------------------------------------------------------
class chat_session
: public chat_participant,
public std::enable_shared_from_this<chat_session>
{
public:
chat_session(tcp::socket socket, chat_room& room)
: socket_(std::move(socket)),
timer_(socket_.get_executor()),
room_(room)
{
timer_.expires_at(std::chrono::steady_clock::time_point::max());
}
void start()
{
room_.join(shared_from_this());
co_spawn(socket_.get_executor(),
[self = shared_from_this()]{ return self->reader(); },
detached);
co_spawn(socket_.get_executor(),
[self = shared_from_this()]{ return self->writer(); },
detached);
}
void deliver(const std::string& msg)
{
write_msgs_.push_back(msg);
timer_.cancel_one();
}
private:
awaitable<void> reader()
{
try
{
for (std::string read_msg;;)
{
std::size_t n = co_await asio::async_read_until(socket_,
asio::dynamic_buffer(read_msg, 1024), "\n", use_awaitable);
room_.deliver(read_msg.substr(0, n));
read_msg.erase(0, n);
}
}
catch (std::exception&)
{
stop();
}
}
awaitable<void> writer()
{
try
{
while (socket_.is_open())
{
if (write_msgs_.empty())
{
asio::error_code ec;
co_await timer_.async_wait(redirect_error(use_awaitable, ec));
}
else
{
co_await asio::async_write(socket_,
asio::buffer(write_msgs_.front()), use_awaitable);
write_msgs_.pop_front();
}
}
}
catch (std::exception&)
{
stop();
}
}
void stop()
{
room_.leave(shared_from_this());
socket_.close();
timer_.cancel();
}
tcp::socket socket_;
asio::steady_timer timer_;
chat_room& room_;
std::deque<std::string> write_msgs_;
};
//----------------------------------------------------------------------
awaitable<void> listener(tcp::acceptor acceptor)
{
chat_room room;
for (;;)
{
std::make_shared<chat_session>(
co_await acceptor.async_accept(use_awaitable),
room
)->start();
}
}
//----------------------------------------------------------------------
int main(int argc, char* argv[])
{
try
{
if (argc < 2)
{
std::cerr << "Usage: chat_server <port> [<port> ...]\n";
return 1;
}
asio::io_context io_context(1);
for (int i = 1; i < argc; ++i)
{
unsigned short port = std::atoi(argv[i]);
co_spawn(io_context,
listener(tcp::acceptor(io_context, {tcp::v4(), port})),
detached);
}
asio::signal_set signals(io_context, SIGINT, SIGTERM);
signals.async_wait([&](auto, auto){ io_context.stop(); });
io_context.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
|
0 | repos/asio/asio/src/examples/cpp20 | repos/asio/asio/src/examples/cpp20/invocation/completion_executor.cpp | //
// completion_executor.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 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 "asio.hpp"
#include <concepts>
#include <iostream>
using asio::ip::tcp;
//----------------------------------------------------------------------
// The logging_executor class implements a minimal executor that satisfies the
// requirements for use as a completion executor. This means it may be bound to
// a handler using bind_executor.
class logging_executor
{
public:
// All executors must be no-throw equality comparable.
bool operator==(const logging_executor&) const noexcept = default;
// All executors must provide a const member function execute().
void execute(std::invocable auto handler) const
{
try
{
std::cout << "handler invocation starting\n";
std::move(handler)();
std::cout << "handler invocation complete\n";
}
catch (...)
{
std::cout << "handler invocation completed with exception\n";
throw;
}
}
};
// Confirm that a logging_executor satisfies the executor requirements.
static_assert(asio::execution::executor<logging_executor>);
// Confirm that a logging_executor can be used as a completion executor.
static_assert(std::convertible_to<
logging_executor, asio::any_completion_executor>);
//----------------------------------------------------------------------
int main()
{
asio::io_context io_context(1);
// Post a completion handler to be run immediately.
asio::post(io_context,
asio::bind_executor(logging_executor{},
[]{ std::cout << "post complete\n"; }));
// Start an asynchronous accept that will complete immediately.
tcp::endpoint endpoint(asio::ip::address_v4::loopback(), 0);
tcp::acceptor acceptor(io_context, endpoint);
tcp::socket server_socket(io_context);
acceptor.async_accept(
asio::bind_executor(logging_executor{},
[](auto...){ std::cout << "async_accept complete\n"; }));
tcp::socket client_socket(io_context);
client_socket.connect(acceptor.local_endpoint());
// Set a timer to expire immediately.
asio::steady_timer timer(io_context);
timer.expires_at(asio::steady_timer::clock_type::time_point::min());
timer.async_wait(
asio::bind_executor(logging_executor{},
[](auto){ std::cout << "async_wait complete\n"; }));
io_context.run();
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.