0

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

  • There is no code. We can't say anything but "you did something wrong" – sehe Jun 30 '22 at 19:01
  • code block added...Kindly let me know, in theory, when will beast throw me a invalid handle error – Suresh Ganapathy Jul 05 '22 at 18:19
  • 1
    I found the reason after 2 days of trial and error...!!! responseFile is function parameter...It is going out of scope during http:async_write. When I copied/moved responseFile to a member variable of my class BeastResponse, my async call is successful. So the learning is, 2nd parameter in http:async_write should be a member variable and not a local variable or variable in the function parameter – Suresh Ganapathy Jul 06 '22 at 11:03
  • Good work. I'm sorry I didn't get around to looking at the code block (next time you can @sehe ping people so the get notified). Consider adding your solution as an answer: it may help others find it in the future – sehe Jul 06 '22 at 12:10

1 Answers1

0

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;
     };
  });
 }