Skip to content

Commit

Permalink
chore: httpconnection cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
MatusKysel committed Sep 28, 2023
1 parent 98e3b07 commit c738d4d
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
3 changes: 2 additions & 1 deletion libraries/core_libs/network/include/network/http_server.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,11 @@ class HttpServer : public std::enable_shared_from_this<HttpServer> {
class HttpConnection : public std::enable_shared_from_this<HttpConnection> {
public:
explicit HttpConnection(const std::shared_ptr<HttpServer>& http_server);
virtual ~HttpConnection() = default;
virtual ~HttpConnection() { HttpConnection::stop(); }
boost::asio::ip::tcp::socket& getSocket() { return socket_; }
virtual std::shared_ptr<HttpConnection> getShared();
void read();
void stop();

protected:
std::shared_ptr<HttpServer> server_;
Expand Down
20 changes: 18 additions & 2 deletions libraries/core_libs/network/src/http_server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,19 @@ std::shared_ptr<HttpConnection> HttpConnection::getShared() {
HttpConnection::HttpConnection(const std::shared_ptr<HttpServer> &http_server)
: server_(http_server), socket_(http_server->getIoContext()) {}

void HttpConnection::stop() {
if (socket_.is_open()) {
try {
LOG(server_->log_dg_) << "Closing connection...";
boost::asio::socket_base::linger option(true, 0);
socket_.set_option(option);
socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both);
socket_.close();
} catch (...) {
}
}
}

void HttpConnection::read() {
boost::beast::http::async_read(
socket_, buffer_, request_, [this, this_sp = getShared()](boost::system::error_code const &ec, size_t) {
Expand All @@ -87,8 +100,11 @@ void HttpConnection::read() {
assert(server_->request_processor_);
LOG(server_->log_dg_) << "Received: " << request_;
response_ = server_->request_processor_->process(request_);
boost::beast::http::async_write(socket_, response_,
[this_sp = getShared()](auto const & /*ec*/, auto /*bytes_transfered*/) {});
response_.version(request_.version());
response_.keep_alive(false);
boost::beast::http::async_write(
socket_, response_,
[this_sp = getShared()](auto const & /*ec*/, auto /*bytes_transfered*/) { this_sp->stop(); });
}
});
}
Expand Down

0 comments on commit c738d4d

Please sign in to comment.