I want to write a server that answers HTTP requests. I do not care about HTTPS. If somebody performs a HTTPS request I want to reject the request and continue with other HTTP requests. My code looks as follows:
#include <boost/asio.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <thread>
#include <iostream>
using namespace std;
int main(){
boost::asio::io_context ioc;
boost::asio::ip::tcp::acceptor acceptor(ioc, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v6(), 8000));
boost::beast::flat_buffer request_buffer;
for(;;){
boost::asio::ip::tcp::socket socket(ioc);
acceptor.accept(socket);
boost::beast::http::request<boost::beast::http::string_body> request;
try{
boost::beast::http::read(socket, request_buffer, request);
cout << "OK" << endl;
boost::beast::http::response<boost::beast::http::string_body> response(boost::beast::http::status::ok, request.version());
std::string body = "hello";
response.content_length(body.size());
response.body() = std::move(body);
boost::beast::http::write(socket, response);
}catch(...){
cout << "BAD" << endl;
}
socket.close();
}
}
I run the code and perform in the following order requests using Firefox:
- a http request
- a https request
- a http request
I expect the following server output:
OK
BAD
OK
However, what I get is:
OK
BAD
BAD
BAD
BAD
BAD
BAD
BAD
BAD
BAD
BAD
BAD
BAD
The function that throws is boost::beast::http::read
. However, I do not understand why. Between calls I create a new socket object and therefore my understanding is that the result of the second request should not impact the third. However, obviously my understanding is not correct. Can somebody please explain where my understanding of how ASIO and/or BEAST works is wrong. Thanks :)