Search code examples
boostboost-asioboost-beast

Boost Beast gives "The handle is invalid" error after http:async_write


Initially I got error "The file handle supplied is invalid". This is because my socket was closed. I corrected that error.

Now I get another error "The handle is invalid"....Any idea what could be the issue

Below is my code, which is very simple:

    void BeastResponse::write(http::response<http::file_body> responseFile)
{
    std::cout << "BeastResponse while file write: " << this << std::endl;
 

    auto self = shared_from_this();

    http::async_write(m_stream, responseFile, [self](beast::error_code ec, std::size_t t)
    {
        if (ec)
        {
            std::cout << "File Write Failed" << ": " << ec.message() << std::endl;
            std::cout << t << std::endl;

        }
        else
        {
            std::cout << t << std::endl;
        };
    });
}

Here , t = 4kb when I get the error. So I think async_write after it does the first block of 4kb, my handler or socket is going to a bad state.

If the change to http:write instead of http:async_write, there is no issues


Solution

  • Below code works for me...

     void BeastResponse::write(http::response<http::file_body>&& responseFile)
     {
       std::cout << "BeastResponse while file write: " << this << std::endl;
       auto self = shared_from_this();
     
      // copy file into the member variable, m_response_file
      m_response_file = std::move(responseFile)
    
      // 2nd parameter must be a member variable of BeastResponse
      http::async_write(m_stream, m_response_file, [self](beast::error_code ec, std::size_t t)
      {
         if (ec)
         {
             std::cout << "File Write Failed" << ": " << ec.message() << std::endl;
             std::cout << t << std::endl;
    
         }
         else
         {
             std::cout << t << std::endl;
         };
      });
     }