#include "UdpServer.h" #include "BoostLog.h" #include "boost/endian.hpp" #include #include UdpServer::UdpServer(boost::asio::io_context &io_context) : m_socket(io_context, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 8088)), m_reveiveBuffer(512), m_timer(io_context) { // start recieve. m_socket.async_receive_from( boost::asio::buffer(m_reveiveBuffer), m_remotePoint, std::bind(&UdpServer::reveiveHandler, this, std::placeholders::_1, std::placeholders::_2)); sendData(); boost::system::error_code error; auto address = boost::asio::ip::address::from_string("127.0.0.1", error); if (error) { LOG(error) << error.message(); } else { m_remotePoint = boost::asio::ip::udp::endpoint(address, 1234); } } void UdpServer::reveiveHandler(const boost::system::error_code &error, std::size_t bytes_transferred) { LOG(info) << "Received byte size: " << bytes_transferred << ",remote ip address: " << m_remotePoint.address().to_string() << std::endl; if (error) { LOG(error) << error.message(); return; } handleReceivedBuffer(m_reveiveBuffer); // continue recieve next datagram. m_socket.async_receive_from( boost::asio::buffer(m_reveiveBuffer), m_remotePoint, std::bind(&UdpServer::reveiveHandler, this, std::placeholders::_1, std::placeholders::_2)); } void UdpServer::sendHandler(const boost::system::error_code &error, std::size_t bytes_transferred) { if (error) { LOG(error) << error.message(); } } void UdpServer::handleReceivedBuffer(std::vector &data) { } void UdpServer::sendData() { using namespace std::chrono_literals; static uint32_t index = 0; m_timer.expires_after(1ms); m_timer.async_wait([this](const boost::system::error_code &) { std::random_device rd; // 将用于获得随机数引擎的种子 std::mt19937 gen(rd()); // 以 rd() 播种的标准 mersenne_twister_engine std::uniform_int_distribution distribution(std::numeric_limits::min(), std::numeric_limits::max()); std::array data; data[0] = 0xAA; data[1] = 0xFF; data[2] = 0x55; data[3] = 0x00; auto bigEndian = reinterpret_cast(&data[4]); *bigEndian++ = boost::endian::native_to_big(index++); for (size_t i = 0; i < 100; i++) { *bigEndian++ = boost::endian::native_to_big(distribution(gen)); } m_socket.async_send_to(boost::asio::buffer(data), m_remotePoint, std::bind(&UdpServer::sendHandler, this, std::placeholders::_1, std::placeholders::_2)); sendData(); }); }