From 2217595c6b9f592870bf72c22a2a0059d365cd71 Mon Sep 17 00:00:00 2001 From: badaix Date: Thu, 30 Apr 2020 10:17:14 +0200 Subject: [PATCH] Fix crash when messages are queued --- client/client_connection.cpp | 17 +++++++++++------ client/client_connection.hpp | 4 +++- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/client/client_connection.cpp b/client/client_connection.cpp index 2eef7930..c55bdddb 100644 --- a/client/client_connection.cpp +++ b/client/client_connection.cpp @@ -81,7 +81,7 @@ void ClientConnection::connect(const ResultHandler& handler) } LOG(NOTICE, LOG_TAG) << "Connected to " << socket_.remote_endpoint().address().to_string() << endl; handler(ec); - // getNextMessage(); +// getNextMessage(); #if 0 resolver_.async_resolve(query, host_, cpt::to_string(port_), [this, handler](const boost::system::error_code& ec, tcp::resolver::results_type results) { @@ -138,9 +138,14 @@ void ClientConnection::sendNext() tv t; message.msg->sent = t; message.msg->serialize(stream); - boost::asio::async_write(socket_, streambuf, boost::asio::bind_executor(strand_, [this](boost::system::error_code ec, std::size_t length) { - std::ignore = length; - auto handler = messages_.front().handler; + auto handler = message.handler; + + boost::asio::async_write(socket_, streambuf, boost::asio::bind_executor(strand_, [this, handler](boost::system::error_code ec, std::size_t length) { + if (ec) + LOG(ERROR, LOG_TAG) << "Failed to send message, error: " << ec.message() << "\n"; + else + LOG(TRACE, LOG_TAG) << "Wrote " << length << " bytes to socket\n"; + messages_.pop_front(); if (handler) handler(ec); @@ -152,8 +157,8 @@ void ClientConnection::sendNext() void ClientConnection::send(const msg::message_ptr& message, const ResultHandler& handler) { - boost::asio::post(strand_, [this, message, handler]() { - messages_.push_back({message, handler}); + strand_.post([this, message, handler]() { + messages_.emplace_back(message, handler); if (messages_.size() > 1) { LOG(DEBUG, LOG_TAG) << "outstanding async_write\n"; diff --git a/client/client_connection.hpp b/client/client_connection.hpp index 58507ff0..adb96be1 100644 --- a/client/client_connection.hpp +++ b/client/client_connection.hpp @@ -123,7 +123,6 @@ public: /// @param message the message /// @param timeout the send timeout /// @param handler async result handler with the response message or error - //template <> void sendRequest(const msg::message_ptr& message, const chronos::usec& timeout, const MessageHandler& handler); /// @sa sendRequest with templated response message @@ -161,6 +160,9 @@ protected: boost::asio::io_context::strand strand_; struct PendingMessage { + PendingMessage(const msg::message_ptr& msg, ResultHandler handler) : msg(msg), handler(handler) + { + } msg::message_ptr msg; ResultHandler handler; };