I started to practice using boost asio & boost beast to develop my own basic server and connection class. Recently I've encountered bad_weak_ptr exception and I can't figure out how to manage the problem. Here is the code:
class server : public boost::asio::io_context::service
{
tcp::endpoint endpoint{ boost::asio::ip::address_v6::any(), 7654 };
tcp::acceptor acceptor;
boost::asio::strand<boost::asio::io_context::executor_type> strand;
std::vector<std::weak_ptr<tcp_connection_ui>> connections;
public:
static const boost::asio::execution_context::id id;
explicit tcp_server_ui(boost::asio::io_context& ioc)
: boost::asio::io_context::service{ ioc }
, acceptor{ ioc, endpoint }
, strand{ ioc.get_executor() }
{
}
void run()
{
boost::asio::post(strand, [this] {start_accept(); });
}
void start_accept()
{
tcp::socket socket{ acceptor.get_io_context() };
tcp_connection_ui::pointer new_connection =
tcp_connection_ui::create(std::move(socket));
connections.push_back(new_connection);
acceptor.async_accept(new_connection->web_socket().next_layer(),
boost::asio::bind_executor(strand, std::bind(
&tcp_server_ui::handle_accept,
this, new_connection, std::placeholders::_1)));
}
void handle_accept(tcp_connection_ui::pointer new_connection,
boost::system::error_code ec)
{
if (!ec) {
new_connection->run();
}
start_accept();
}
void broadcast(std::string&& msg)
{
std::cout << '+' << std::endl;
if (connections.empty())
return;
for (auto const & x : connections)
x.lock()->enqueue_message(std::move(msg));
}
};
And there is the place where the code stops running:
class tcp_connection_ui : std::enable_shared_from_this<tcp_connection_ui>
{
public:
using pointer = std::shared_ptr<tcp_connection_ui>;
static pointer create(tcp::socket socket)
{
return std::make_shared<tcp_connection_ui>(tcp_connection_ui{ std::move(socket) });
}
void run()
{
ws.async_accept(boost::asio::bind_executor(strand, std::bind(
&tcp_connection_ui::on_accept, shared_from_this(),
std::placeholders::_1)));
} .../};
If the client tries to connect the value shared_from_this in server::handle_accept is equal to _Wptr = empty. I think i have some troubles with understanding io_context::service and/or shared_from_this feature. Any help would be appreciated.
The base class must be inherited publicly:
class tcp_connection_ui : public std::enable_shared_from_this<tcp_connection_ui>
Otherwise, make_shared
or shared_ptr
will not notice it and subsequently fail to initialize the "hidden" weak_ptr