通过 Boost ASIO 发送大文本

Sending a large text via Boost ASIO

我正在尝试向我的一位客户发送一个非常大 的字符串。我主要遵循 HTTP 服务器示例中的代码:https://www.boost.org/doc/libs/1_78_0/doc/html/boost_asio/examples/cpp11_examples.html

使用错误代码 14 编写回调 return,根据此 link:

,这可能意味着 EFAULT,“地址错误”

https://mariadb.com/kb/en/operating-system-error-codes/

请注意,我无法使用 error_code 的 message() 成员函数来读取错误消息,这是导致分段错误的原因。 (我使用的是Boost 1.53,错误可能是因为:https://github.com/boostorg/system/issues/50

当我尝试发送小字符串时,例如大小为 10,写入回调不会 return 并出现错误。

我是这样使用的 async_write:

void Connection::do_write(const std::string& write_buffer)
{
  auto self(shared_from_this());
  boost::asio::async_write(socket_, boost::asio::buffer(write_buffer, write_buffer.size()),
      [this, self, write_buffer](boost::system::error_code ec, std::size_t transfer_size)
      {
        if (!ec)
        {

        } else {
          // code enters here **when** I am sending a large text.
          // transfer_size always prints 65535
        }
      });
}

我是这样使用的 async_read_some:

void Connection::do_read()
{
  auto self(shared_from_this());
  socket_.async_read_some(boost::asio::buffer(buffer_),
      [this, self](boost::system::error_code ec, std::size_t bytes_transferred)
      {
        if (!ec)
        {
           do_write(VERY_LARGE_STRING);
           do_read();
        } else if (ec != boost::asio::error::operation_aborted) {
          connection_manager_.stop(shared_from_this());
        }
      });
}

什么可能导致写入回调到 return 并出现大字符串错误?

段错误对我来说可能 Undefined Behaviour

当然没有多少代码可以说明,但是你使用对 non-member 的引用作为缓冲区有一种强烈的气味:

boost::asio::buffer(write_buffer, write_buffer.size())

除了可以简单地拼写为 boost::asio::buffer(writer_buffer) 之外,write_buffer 在依赖于它的异步操作期间保持不变的希望不大。

作为文档 states:

Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.

我会检查您是否正确执行此操作。

UB 的另一个潜在原因是 when you cause overlapping writes 在同一个 socket/stream 对象上:

This operation is implemented in terms of zero or more calls to the stream's async_write_some function, and is known as a composed operation. The program must ensure that the stream performs no other write operations (such as async_write, the stream's async_write_some function, or any other composed operations that perform writes) until this operation completes.

如果您检查了这两个问题并发现一定有问题,请 post 一个新问题,包括一个完全独立的示例 (SSCCE or MCVE)