I trying to build a server-client application the server-side is c++ with boost::asio async but when I'm running the application it gets stuck after 1 reading and two writes.
this is the relevant code when I'm removing the do_write
function call I'm getting all 5 messages that I'm sending
EDIT when I'm running with a debugger I'm able to receive all five messages and send all the response
void start()
{
std::thread t1([this](){do_write();});
t1.detach();
std::thread t2([this](){do_read();});
t2.detach();
}
void do_write()
{
auto self(shared_from_this());
Message msg;
while(order_response_queue_.empty())
{}
auto order_response = order_response_queue_.front();
order_response_queue_.pop();
try {
auto m = order_response.SerializeToString();
msg.body_length(std::strlen(m.c_str()));
std::memcpy(msg.body(), m.c_str(), std::strlen(m.c_str()));
msg.encode_header();
std::memcpy(data_,msg.data(), msg.length());
//std::memcpy(static_cast<void *>(msg.data()), data_, msg.length());
} catch (std::exception& e )
{
std::cout << e.what();
}
std::cout <<"write: " << msg.body() << "\n";
boost::asio::async_write(socket_, boost::asio::buffer(data_,msg.length()),
[this, self](boost::system::error_code ec, std::size_t /*length*/)
{
if (ec){
std::cerr << "write error:" << ec.value() << " message: " << ec.message() << "\n";
}
do_write();
});
}
void do_read()
{
auto self(shared_from_this());
Message msg;
socket_.async_read_some(boost::asio::buffer(res.data(), res.header_length),
[this, self](boost::system::error_code ec, std::size_t length) {
if (!ec && res.decode_header()) {
std::string st(res.body());
boost::asio::async_read(socket_, boost::asio::buffer(res.body(), res.body_length()), [this](boost::system::error_code ec, std::size_t length) {
if (!ec) {
std::cout << "read " << res.body() << "\n";
req_.DeserializeFromChar(res.body());
order_request_queue_.push(req_);
} else {
if (ec) {
std::cerr << "read error:" << ec.value() << " message: "
<< ec.message() << "\n";
}
socket_.close();
}
});
}
do_read();
});
}
here is the io_service
class Server
{
public:
Server(boost::asio::io_service& io_service, short port,std::queue<OrderRequest> &order_request_queue,
std::queue<OrderResponse> &order_response_queue)
: acceptor_(io_service, tcp::endpoint(tcp::v4(), port)),
socket_(io_service) , order_response_queue_(order_response_queue), order_request_queue_(order_request_queue)
{
do_accept();
}
private:
void do_accept(){
acceptor_.async_accept(socket_,
[this](boost::system::error_code ec) {
if (!ec) {
std::cout << "accept connection\n";
std::make_shared<Session>(std::move(socket_),order_request_queue_, order_response_queue_)->start();
}
do_accept();
});
}
tcp::acceptor acceptor_;
tcp::socket socket_;
std::queue<OrderResponse> &order_response_queue_;
std::queue<OrderRequest> &order_request_queue_;
};