首页 > 解决方案 > C++ / ASIO / TCP / Socket / Response 有时/经常是空的,即使 do_write 被成功调用

问题描述

我有一个关于 asio 和 TCP 套接字的问题。

目前我正在使用async_read_until直到有两个“\n\n”的序列。如果没有错误,我会做一些数据库工作并向客户端返回响应。这基本上是使用 asio 示例完成的。我的问题是:如果我遇到错误(asio::error_code& ec != null),那么我如何确保我可以将答案写回给客户?因为如果我确实从错误条件中调用 do_write(...) ,则大约一半的响应不会到达客户端。

void do_read (some data) {
asio::async_read_until(socket_, buf_, "\n\n",
            [this, self](const asio::error_code& ec, std::size_t bytes_transferred)
 {
  if(ec) {
    do_write("This answer does not reach the client 50% of the time, sometimes more; sometimes less");
  } else {
    do_write("You did well my young apprentice! Always works");
  }
 });
}

void do_write(const std::string& response) {
  asio::async_write(socket_, asio::buffer(response.c_str(), response.length()),
    [this, self, response](std::error_code ec, std::size_t bytes_transferred) {
      if (ec) {
        // no error here whats-o-ever!
      } else {
        // OK: bytes_transferred == response.size()
      }
    }
}

当然我在这里做错了什么,但是什么?起初我认为这都是异步的,所以参数可能超出了范围。但是do_write无论 ec == null 是什么都被调用,我什至使用逐字字符串对其进行测试,就像在这个例子中一样。

标签: c++asio

解决方案


推荐阅读