#pragma once #include #include #include #include "protocol.hpp" #include "spdlog/spdlog.h" namespace commons { using boost::asio::ip::udp; using namespace protocol; class server { public: server(boost::asio::io_context& io_context, short port) : socket_(io_context, udp::endpoint(udp::v4(), port)) { do_receive(); } void do_receive() { spdlog::debug("do receive"); socket_.async_receive_from( boost::asio::buffer(data_, max_length), sender_endpoint_, [this](boost::system::error_code ec, std::size_t bytes_recvd) { if (!ec && bytes_recvd > 0) { std::cout << data_ << std::endl; auto* msg_obj = reinterpret_cast( data_); spdlog::debug("Object Type: {}", static_cast(msg_obj->get_type())); spdlog::debug("Object Size: {}", msg_obj->get_size()); auto* casted_obj = reinterpret_cast(msg_obj); spdlog::debug("Position: X = {}, Y = {}", casted_obj->position.x, casted_obj->position.y); do_send(bytes_recvd); } else { do_receive(); } }); } void do_send(std::size_t length) { socket_.async_send_to(boost::asio::buffer(data_, length), sender_endpoint_, [this](boost::system::error_code /*ec*/, std::size_t /*bytes_sent*/) { do_receive(); }); } private: udp::socket socket_; udp::endpoint sender_endpoint_; enum { max_length = 1024 }; char data_[max_length]; }; } // namespace commons