E
E
Elnurhan2021-02-02 12:27:48
C++ / C#
Elnurhan, 2021-02-02 12:27:48

How to read the entire http request along with the body?

Hello!
I ran into such a problem: I am writing a simple http server, and when a POST request with a body comes to me, the request without the body is read first, and then, separately, the body is read.
So, for example, I have a query like this:

POST / HTTP/1.1
Host: ....
Connection: keep-alive
Content-Length: 11

hello world

And I read it like this:
void TCPConnection::startReceiving()
{
    m_socket.async_receive(boost::asio::buffer(m_buffer),
            boost::bind(&TCPConnection::handleReceive, shared_from_this(), _1, _2));
}
        ...
void TCPConnection::handleReceive(const boost::system::error_code ec, size_t bytesTransferred)
{
    if (ec)
        return;
    
    handler(&m_buffer.front(), bytesTransferred); // Handler for processing some data.
    startReceiving();
}

And first, the header is read up to the characters "\r\n\r\n":
POST / HTTP/1.1
Host: ....
Connection: keep-alive
Content-Length: 11

Then the body is read:
hello world

Is there any way to read this entire request in its entirety?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav Makarov, 2021-02-02
@Nipheris

async_receive :

The receive operation may not receive all of the requested number of bytes. Consider using the async_read function if you need to ensure that the requested amount of data is received before the asynchronous operation completes.

But since you don't know in advance how many bytes you need to read anyway, I don't see a problem with async_receive behavior. You need to keep track of the state of your protocol (in your case, HTTP) and understand when you need to wait for more data, and when everything has already arrived.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question