I have minor experience with c++ and facing some issue with boost-asio.
I want to rewrite standard boost-asio async-http-client example (http://www.boost.org/doc/libs/1_58_0/doc/html/boost_asio/example/cpp03/http/client/async_client.cpp) in following way.
My goal is to have 2 classes;
AsyncHttpClient(that stores host and has member function that will send async calls to specified path).
AsyncHttpConnection (that takes io_service, host, path as parameters
and follows the flow specified in boost-asio async-http-client
example)
I have the following implementation
using boost::asio::ip::tcp;
class AsyncHttpConnection {
public:
AsyncHttpConnection(
boost::asio::io_service& io_service,
std::string host,
std::string path) : resolver_(io_service),
socket_(io_service),
host_(host),
path_(path)
{
tcp::resolver::query query(host_, "http");
resolver_.async_resolve(query,
boost::bind(&AsyncHttpConnection::handle_resolve,
this,
boost::asio::placeholders::error,
boost::asio::placeholders::iterator));
}
private:
std::string host_;
std::string path_;
tcp::resolver resolver_;
tcp::socket socket_;
boost::asio::streambuf request_;
boost::asio::streambuf response_;
void handle_resolve(
const boost::system::error_code& err,
tcp::resolver::iterator endpoint_iterator)
{
if (!err) {
// code here
} else {
std::cout << err.message() << std::endl; // GOT "Operation Canceled" here
}
}
// list of other handlers
};
class AsyncHttpClient {
public:
AsyncHttpClient(
boost::asio::io_service& io_service,
std::string host) : host_(host)
{
io_service_ = &io_service; // store address of io_service
}
void async_call(std::string path)
{
AsyncHttpConnection(*io_service_, host_, path);
}
private:
std::string host_;
boost::asio::io_service* io_service_; // pointer, because io_service is uncopyable;
};
int main(int argc, char* argv[])
{
boost::asio::io_service io_service;
AsyncHttpClient boost(io_service, "www.boost.org");
boost.async_call("/doc/libs/1_51_0/doc/html/boost_asio/example/http/client/async_client.cpp");
io_service.run();
}
I got an error "Operation Canceled" in this particular way;
If I instantiate AsyncHttpConnection in following way
int main(int argc, char* argv[])
{
boost::asio::io_service io_service;
AsyncHttpConnection(io_service, "www.boost.org", "path");
io_service.run();
}
I got everything working perfectly, I think the issue is using pointer to io_service. How can I solve this issue, if io_service object is uncopyable?
void async_call(std::string path) {
AsyncHttpConnection(*io_service_, host_, path);
}
The body constructs a temporary object of type AsyncHttpConnection. So, before the statement completes, the destructor for this type runs.
The default destructor does member-wise destruction. So it triggers the destructor tcp::resolver resolver_. The documentation for this class states that any pending asynchronous operation will be canceled on doing so.
In principle the "alternative" main has exactly the same problem (and indeed it fails with Operation canceled on my box). If it doesn't for you you're getting very fortunate timing of events.
Related
i have this socket-tcp.h with an wrapper of socket implementation using boost asio:
#include <boost/asio.hpp>
#include <iostream>
#include <boost/thread.hpp>
static const std::string PORT = "65432";
static const std::string HOST = "127.0.0.1";
struct Client
{
boost::asio::io_service& io_service;
boost::asio::ip::tcp::socket socket;
Client(boost::asio::io_service& svc, std::string const& host, std::string const& port)
: io_service(svc), socket(io_service)
{
boost::asio::ip::tcp::resolver resolver(io_service);
boost::asio::ip::tcp::resolver::iterator endpoint = resolver.resolve(boost::asio::ip::tcp::resolver::query(host, port));
boost::asio::connect(this->socket, endpoint);
};
void send(std::string const& message) {
socket.send(boost::asio::buffer(message));
}
};
boost::asio::io_service svc;
Client client(svc, HOST, PORT);
class TcpSocket
{
private:
std::string HOST;
std::string PORT;
public:
TcpSocket (std::string const& host, std::string const& port): HOST{ host },PORT{ port }
{
}
void send(std::string const& message)
{
boost::thread t(client_thread,boost::ref(message),boost::ref(HOST),boost::ref(PORT));
t.join();
}
static void client_thread(std::string const& message,std::string const& host,std::string const& port)
{
client.send(message);
}
};
so that my main file looks like:
#include "socket-tcp.h"
int main()
{
TcpSocket socket(PORT,HOST);
std::string message = "socket implemented using global variables";
while (true)
{
socket.send(message);
}
}
I'm trying to figure out a way of implement this without the global variables
boost::asio::io_service svc;
Client client(svc, HOST, PORT);
such that TcpSocket be like:
class TcpSocket
{
//Object* myObject; // Will not try to call the constructor or do any initializing
//myObject = new Object(...); // Initialised now
private:
std::string HOST;
std::string PORT;
boost::asio::io_service svc;
public:
TcpSocket (std::string const& host, std::string const& port): HOST{ host },PORT{ port }
{
Client client(svc, HOST, PORT);
}
void send(std::string const& message)
{
boost::thread t(client_thread,boost::ref(message),boost::ref(HOST),boost::ref(PORT));
t.join();
}
static void client_thread(std::string const& message,std::string const& host,std::string const& port)
{
client.send(message);
}
};
but i end up with the runtime error:
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::system::system_error> >'
what(): resolve: Service not found
is there a way to avoid using these global variables (objects), and keeping the same socket open all the time, without closing and opening it again at each new message?
I accept better implementations or suggestions for this wrapper, but the goal is to keep main as simple and clear as possible.
The "service not found" merely means that the port is not a valid service. That's because you swapped host and port parameters.
But that is the least of your worries.
You're playing fast and loose with object lifetimes. For example, you pass message all the way to another thread &&by reference** (std::string const&), but the object referenced lives on the stack (as a function argument) so that invokes Undefined Behaviour.
Besides, it's not clear how the thread (or client_thread) is supposed to access the Client instance (that your code constructs as a local variable in the TcpSocket constructor only). Let alone that it would be unsafe to share that client across threads.
Medium Fix
Live On Coliru
#include <boost/asio.hpp>
#include <iostream>
#include <boost/thread.hpp>
static const std::string HOST = "127.0.0.1";
static const std::string PORT = "65432";
using boost::asio::ip::tcp;
struct Client
{
tcp::socket socket;
//template <typename Executor>
using Executor = boost::asio::io_service&;
Client(Executor executor, std::string const& host, std::string const& port)
: socket(executor)
{
std::cout << std::quoted(host) << std::endl;
std::cout << std::quoted(port) << std::endl;
auto ep = tcp::resolver{socket.get_executor()}.resolve(host, port);
connect(socket, ep);
};
void send(std::string const& message) {
socket.send(boost::asio::buffer(message));
}
};
class TcpSocket {
private:
std::string _host;
std::string _port;
boost::asio::io_service _svc;
public:
TcpSocket(std::string const& host, std::string const& port)
: _host{host}
, _port{port}
{
}
void send(std::string const& message)
{
boost::thread t( //
client_thread, boost::ref(_svc), message, _host, _port);
t.join();
}
static void client_thread( //
boost::asio::io_service& svc,
std::string message, // NOT A REFERENCE
std::string host, // same
std::string port)
{
Client client(svc, host, port);
client.send(message);
}
};
//#include "socket-tcp.h"
int main()
{
TcpSocket socket(HOST, PORT);
std::string const message = "socket implemented using global variables";
while (true) {
socket.send(message);
}
}
More Notes
The thread is by definition useless, since you join it immediately. But if you really wanted that, please consider c++11 style:
void send(std::string const& message)
{
boost::thread t([=, &_svc] {
Client client(_svc, _host, _port);
client.send(message);
});
t.join();
}
It makes far more sense to do it on the main thread:
void send(std::string const& message)
{
Client client(_svc, _host, _port);
client.send(message);
}
Or to use async IO. Note that you should probably prefer to pass executors rather than sharing references to an execution context. Also, prefer io_context because io_service is deprecated.
Here's a simplified program that still does the same: Live On Coliru
BONUS - Async With A Thread Pool
Seems like you wanted the messages to be delivered in async fashion. However, you didn't know how to get threads in the background. Regardless, it wouldn't be a safe idea to "just create a new thread" each time. The professional approach is to use a thread pool.
This example uses a ddefault boost::asio::thread_pool and throws in a strand (even though it's not currently required) and a Session object to hold all the state for a single message. Note that we now cache the resolver results. That can be a good thing ,or a bad thing depending on your application.
Live On Coliru
#include <boost/asio.hpp>
#include <iostream>
#include <boost/thread.hpp>
#include <boost/enable_shared_from_this.hpp>
using boost::asio::ip::tcp;
using boost::system::error_code;
class TcpClient {
public:
TcpClient(std::string const& host, std::string const& port)
: _ep(tcp::resolver{_io}.resolve(host, port))
{ }
void send(std::string message)
{
boost::make_shared<Session>( //
make_strand(_io.get_executor()), std::move(message), _ep)
->run();
}
~TcpClient() {
//_io.stop(); // optionally
_io.join();
}
private:
boost::asio::thread_pool _io;
tcp::resolver::results_type _ep ;
struct Session : boost::enable_shared_from_this<Session> {
Session(auto executor, std::string message,
tcp::resolver::results_type ep)
: _socket(executor)
, _message(std::move(message))
, _ep(ep)
{
}
void run() {
async_connect( //
_socket, _ep,
[this, self = shared_from_this()](error_code ec,
tcp::endpoint) {
async_write(_socket, boost::asio::buffer(_message),
[this, self](error_code ec, size_t) {});
});
}
tcp::socket _socket;
std::string _message;
tcp::resolver::results_type _ep;
};
};
//#include "socket-tcp.h"
int main()
{
TcpClient socket("127.0.0.1", "65432");
for (int i = 0; i<100; ++i) {
socket.send("socket implemented using async IO on thread pool " +
std::to_string(i) + "\n");
}
}
All of the boost examples work until I try to implement the exact same thing myself. I'm starting to think there must be an order of creation or io_service ownership for things to block properly.
My server structure is as follows:
class Server {
public:
Server(unsigned short port)
: ioService_(), acceptor_(ioService_), socket_(ioService_) {
acceptClient(); // begin async accept
}
void start(); // runs ioService_.run();
private:
void acceptClient();
asio::io_service ioService_;
tcp::acceptor acceptor_;
tcp::socket socket_;
Cluster cluster_; // essentially just a connection manager
};
The acceptClient() function works like this:
void Server::acceptClient() {
acceptor_.async_accept(socket_, [this](const system::error_code& e){
if(!acceptor_.is_open()) return;
if(!e) {
cluster_.add(std::make_shared<Client>(std::move(socket_), cluster_));
}
acceptClient();
});
}
I'm not sure if you need an outline of the Client class since the server should run and block even with no clients.
The creation of the server goes as follows:
try {
Server server(port);
server.start(); // this calls the server's member io_service's run();
} catch (const std::exception& e) {
std::cerr << e.what(); << std::endl;
}
The problem is the server instantly closes after that call. The program starts and then exits with no errors. Is there something that io_service.run() relies on? e.g. some form of asynchronous link that I've forgotten? My learned this design from boost asio's http server design but I've worked it to fit my basic purposes. The problem is some boost examples establish a new member boost tcp::socket in the client itself rather than moving the server's to the client so I'm quite confused. They also tend to use boost's versions of std::bind instead of lambdas which etc.
So, can anyone give me a brief rundown on how to create a basic, stripped, async server since the boost examples are really confusing since the code conventions differ per example. I was wondering if anybody noticed anything straight away that would cause my server to instantly close.
Thanks.
I tested async_accept with the following code which sends Hello to clients connecting to the port. At least there is the creation of endpoint object, acceptor.open(endpoint.protocol()), acceptor.bind(endpoint) and acceptor.listen() calls that seem to be missing from your code.
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <string>
using namespace boost::asio;
void handle_accept(
io_service * ios,
ip::tcp::acceptor * acceptor,
ip::tcp::socket * socket,
const boost::system::error_code & error)
{
if (!error) {
std::string msg("Hello\n");
socket->send(buffer(msg, msg.length()));
ip::tcp::socket * temp = new ip::tcp::socket(*ios);
acceptor->async_accept(*temp,
boost::bind(handle_accept,
ios, acceptor, temp,
placeholders::error));
}
}
int main(void)
{
io_service ios;
ip::tcp::socket socket(ios);
ip::tcp::acceptor acceptor(ios);
ip::tcp::endpoint endpoint(ip::tcp::v4(), 1500);
acceptor.open(endpoint.protocol());
acceptor.set_option(ip::tcp::acceptor::reuse_address(true));
acceptor.bind(endpoint);
acceptor.listen();
acceptor.async_accept(socket,
boost::bind(handle_accept,
&ios, &acceptor, &socket,
placeholders::error));
ios.run();
/*
acceptor.accept(socket);
std::string msg("Hello\n");
socket.send(buffer(msg, msg.length()));
*/
}
A version with a Server class and a lambda as a argument for async_accept:
#include <boost/asio.hpp>
#include <functional>
#include <string>
using namespace boost::asio;
class Server {
public:
Server(unsigned short port) : ios(), acceptor(ios), socket(ios),
endpoint(ip::tcp::v4(), port) {
acceptor.open(endpoint.protocol());
acceptor.set_option(ip::tcp::acceptor::reuse_address(true));
acceptor.bind(endpoint);
acceptor.listen();
nsocket = &socket;
}
void run() {
std::function<void (const boost::system::error_code &)> f;
f = [&f, this] (const boost::system::error_code & error) {
if (!error) {
std::string msg("Hello\n");
nsocket->send(buffer(msg, msg.length()));
nsocket = new ip::tcp::socket(ios);
acceptor.async_accept(*nsocket, f);
}
};
acceptor.async_accept(socket, f);
ios.run();
}
protected:
io_service ios;
ip::tcp::acceptor acceptor;
ip::tcp::socket socket;
ip::tcp::endpoint endpoint;
ip::tcp::socket * nsocket;
};
int main(void)
{
Server srv(1500);
srv.run();
}
I have the following error:
Error C2280 'Sender::Sender(const Sender &)': attempting to reference a deleted function
This is my code:
#pragma once
#include <iostream>
#include <string>
#include "asio.hpp"
using namespace asio;
class Sender
{
public:
Sender(io_service& io_service,
const std::string& host,
const std::string& port) :
io_service_(io_service),
socket_(io_service, ip::udp::endpoint(ip::udp::v4(), 0))
{
ip::udp::resolver resolver(io_service_);
ip::udp::resolver::query query(ip::udp::v4(), host, port);
ip::udp::resolver::iterator iter = resolver.resolve(query);
endpoint_ = *iter;
};
~Sender()
{
socket_.close();
};
void operator()()
{
std::string msg = "";
for (;;)
{
std::cout << "Message: ";
std::cin >> msg;
std::cout << "The value you entered is " << msg << std::endl;
}
}
private:
io_service& io_service_;
ip::udp::socket socket_;
ip::udp::endpoint endpoint_;
};
And I'm calling it like this:
io_service io_service;
Sender s{ io_service, "localhost", "1337" };
std::thread sender_thread{ s };
sender_thread.join();
I know that it's because one of the private members can't be copied, but I can't figure out how to fix it! I don't want to implement a copy constructor.
Sender is moveable but not copyable because boost::asio's socket is moveable but not copyable (see documentation).
You will need to std::move() your sender into the thread's constructor.
This is a SSCCE from my Boost.Asio project based on the examples. It took me about an hour to track the bug down to this:
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
class Connection {
public:
Connection(boost::asio::io_service& io_service) : socket(io_service) {}
private:
boost::asio::ip::tcp::socket socket;
};
class Server {
public:
Server() : signal_monitor(io_service) {
signal_monitor.add(SIGINT);
signal_monitor.add(SIGTERM);
signal_monitor.async_wait(
boost::bind(&Server::handle_signal_caught, this)
);
}
void run() {
// comment out the next line and there's no segfault
connection.reset(new Connection(io_service));
io_service.run();
}
private:
void handle_signal_caught() {
io_service.stop();
}
boost::shared_ptr<Connection> connection;
boost::asio::io_service io_service;
boost::asio::signal_set signal_monitor;
};
int main(int argc, char **argv) {
Server server;
server.run();
return 0;
}
When I send a signal (ctrl+C) the program segfaults instead of shutting down nicely. I've spent the last half hour looking at this, but I simply do not see why this would segfault, can any of you guys spot the issue?
I think I found out the issue. Note the declaration order of the members of Server:
boost::shared_ptr<Connection> connection;
boost::asio::io_service io_service;
boost::asio::signal_set signal_monitor;
Destruction order is done in the opposite order of declaration. This means that first signal_monitor, then io_service and finally connection get destroyed. But connection contains a boost::asio::ip::tcp::socket containing a reference to io_service, which got destroyed.
And indeed, this is pretty much what happening, and causes a segfault too:
int main(int argc, char **argv) {
auto io_service = new boost::asio::io_service();
auto socket = new boost::asio::ip::tcp::socket(*io_service);
delete io_service;
delete socket;
return 0;
}
Declaring connection after io_service solves the issue.
Damn
I'm trying to implement a simple client/server in ASIO.
I'd like the following on the serverside:
onConnect()
onDisconnect()
onMessageRecieved(char* data)
sendMessage(char* data)
and on the client side:
onConnect()
onDisconnect()
onMessageRecieved(char* data)
sendMessage(char* data)
I didn't realise things would be so complicated.
Here's the simple echo server which I'm working off of:
#include <cstdlib>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
class session
{
public:
session(boost::asio::io_service& io_service)
: socket_(io_service)
{
}
tcp::socket& socket()
{
return socket_;
}
void start()
{
socket_.async_read_some(boost::asio::buffer(data_, max_length),
boost::bind(&session::handle_read, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void handle_read(const boost::system::error_code& error,
size_t bytes_transferred)
{
if (!error)
{
boost::asio::async_write(socket_,
boost::asio::buffer(data_, bytes_transferred),
boost::bind(&session::handle_write, this,
boost::asio::placeholders::error));
}
else
{
delete this;
}
}
void handle_write(const boost::system::error_code& error)
{
if (!error)
{
socket_.async_read_some(boost::asio::buffer(data_, max_length),
boost::bind(&session::handle_read, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
else
{
delete this;
}
}
private:
tcp::socket socket_;
enum { max_length = 1024 };
char data_[max_length];
};
class server
{
public:
server(boost::asio::io_service& io_service, short port)
: io_service_(io_service),
acceptor_(io_service, tcp::endpoint(tcp::v4(), port))
{
session* new_session = new session(io_service_);
acceptor_.async_accept(new_session->socket(),
boost::bind(&server::handle_accept, this, new_session,
boost::asio::placeholders::error));
}
void handle_accept(session* new_session,
const boost::system::error_code& error)
{
if (!error)
{
new_session->start();
new_session = new session(io_service_);
acceptor_.async_accept(new_session->socket(),
boost::bind(&server::handle_accept, this, new_session,
boost::asio::placeholders::error));
}
else
{
delete new_session;
}
}
private:
boost::asio::io_service& io_service_;
tcp::acceptor acceptor_;
};
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: async_tcp_echo_server <port>\n";
return 1;
}
boost::asio::io_service io_service;
using namespace std; // For atoi.
server s(io_service, atoi(argv[1]));
io_service.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
I can telnet into this server and everything is echoed.
Now I'd like to wrap up this code in onConnect(), onDisconnect(), onMessageReceived(char* data), etc. Similar to the way things are done in Node.js!
Has anyone got any pointers in this regard?
onMessageReceived() can be called from handle_read.
onConnect() can be called from start.
onDisconnect() can be called in the destructor of the session class.
For the bounty questions:
The io_service.run() can be placed in its own thread.
As per the documentation
Certain guarantees are made on when the handler may be invoked, in particular that a handler can only be invoked from a thread that is currently calling run() on the corresponding io_service object.
Asynchronous sending and receiving can be handled by this single thread. This simplifies thread safety because all the callbacks will be running in succession. This is probably the simplest way of using boost asio.
For calls coming from outside of the run() thread, you can schedule a callback (e.g. deadline_timer), from the 'outside thread' for immediate calling to simplify your thread safety handling. e.g.
boost::asio::deadline_timer timer(io_service);
timer.expires_from_now(boost::posix_time::seconds(0));
timer.async_wait(boost::bind(&MyClass::MyCallback, this, boost::asio::placeholders::error);
The io_service object will call the handler for you in a thread-safe fashion as soon as it has a chance. This way, your asio code can behave as if there was only a single thread in the entire system.
If multiple threads are required or preferred (e.g. Take advantage of multi-core) you may call run() on multiple thread. Handlers will have to be re-entrant. You may also want to use a strand for certain operations.
Otherwise, regular thread safety rules applies.