Kylin/HttpProxy/ProxyListener.cpp
2023-07-21 15:28:59 +08:00

52 lines
1.6 KiB
C++

#include "ProxyListener.h"
#include "BoostLog.h"
#include "ProxyHttpSession.h"
#include <boost/asio/strand.hpp>
#include <boost/beast/core.hpp>
ProxyListener::ProxyListener(boost::asio::io_context &ioContext, boost::asio::ip::tcp::endpoint endpoint)
: m_ioContext(ioContext), m_acceptor(m_ioContext), m_endpoint(std::move(endpoint)) {
}
void ProxyListener::run(boost::system::error_code &error) {
m_acceptor.open(m_endpoint.protocol(), error);
if (error) {
LOG(error) << error.message();
return;
}
m_acceptor.set_option(boost::asio::ip::tcp::socket::reuse_address(true), error);
if (error) {
LOG(error) << error.message();
return;
}
m_acceptor.bind(m_endpoint, error);
if (error) {
LOG(error) << error.message();
return;
}
m_acceptor.listen(boost::asio::ip::tcp::socket::max_connections, error);
if (error) {
LOG(error) << error.message();
return;
}
doAccept();
}
void ProxyListener::doAccept() {
m_acceptor.async_accept(
boost::asio::make_strand(m_ioContext),
[ptr{weak_from_this()}](boost::beast::error_code error, boost::asio::ip::tcp::socket socket) {
if (ptr.expired()) return;
auto self = ptr.lock();
if (error) {
LOG(error) << error.message();
return;
}
auto session = std::make_shared<ProxyHttpSession>(self->m_ioContext, std::move(socket));
session->run();
self->doAccept();
});
}