5#include <spdlog/spdlog.h>
10 const std::string &host, uint16_t port,
bool is_server)
11 : socket_(io_context_), host_(host), port_(port), is_server_(is_server) {
13 "Initializing SocketTransport with host: {} and port: {}", host, port);
27 spdlog::info(
"Closing socket and shutting down SocketTransport.");
31 spdlog::warn(
"Socket close error: {}", ec.message());
36void SocketTransport::Connect() {
37 asio::ip::tcp::resolver resolver(io_context_);
38 auto endpoints = resolver.resolve(host_, std::to_string(port_));
40 asio::steady_timer timer(io_context_);
41 timer.expires_after(std::chrono::seconds(3));
43 std::error_code connect_error;
46 [&](
const asio::error_code &error,
const asio::ip::tcp::endpoint &) {
50 connect_error = error;
54 timer.async_wait([&](
const asio::error_code &error) {
56 connect_error = asio::error::timed_out;
65 "Error connecting to {}:{}. Error: {}", host_, port_,
66 connect_error.message());
67 throw std::runtime_error(
"Error connecting to socket");
71void SocketTransport::BindAndListen() {
73 asio::ip::tcp::acceptor acceptor(
74 io_context_, asio::ip::tcp::endpoint(asio::ip::tcp::v4(), port_));
76 spdlog::info(
"Listening on {}:{}", host_, port_);
77 acceptor.accept(socket_);
78 spdlog::info(
"Accepted connection on {}:{}", host_, port_);
79 }
catch (
const std::exception &e) {
81 "Error binding/listening on {}:{}. Error: {}", host_, port_, e.what());
82 throw std::runtime_error(
"Error binding/listening on socket");
88 asio::write(socket_, asio::buffer(message +
"\n"));
89 spdlog::debug(
"Sent message: {}", message);
90 }
catch (
const std::exception &e) {
91 spdlog::error(
"Error sending message: {}", e.what());
92 throw std::runtime_error(
"Error sending message");
98 asio::streambuf buffer;
99 asio::read_until(socket_, buffer,
'\n');
100 std::istream is(&buffer);
102 std::getline(is, message);
103 spdlog::debug(
"Received message: {}", message);
105 }
catch (
const std::exception &e) {
106 spdlog::error(
"Error receiving message: {}", e.what());
~SocketTransport() override
auto GetSocket() -> asio::ip::tcp::socket &
void SendMessage(const std::string &message) override
Sends a message in string to the transport layer.
SocketTransport(const std::string &host, uint16_t port, bool is_server)
Constructs a SocketTransport.
auto ReceiveMessage() -> std::string override
Receives a message from the transport layer.