1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| #define _CRT_SECURE_NO_WARNINGS #include <ctime> #include <iostream> #include <string> #include <boost/array.hpp> #include <boost/bind/bind.hpp> #include <boost/shared_ptr.hpp> #include <boost/asio.hpp>
using boost::asio::ip::udp;
std::string make_daytime_string() { using namespace std; time_t now = time(0); return ctime(&now); }
class udp_server { public: udp_server(boost::asio::io_context& io_context) : socket_(io_context, udp::endpoint(udp::v4(), 13)) { start_receive(); }
private: void start_receive() { socket_.async_receive_from( boost::asio::buffer(recv_buffer_), remote_endpoint_, boost::bind(&udp_server::handle_receive, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } void handle_receive(const boost::system::error_code& error, std::size_t ) { if (!error) { boost::shared_ptr<std::string> message( new std::string(make_daytime_string())); socket_.async_send_to(boost::asio::buffer(*message), remote_endpoint_, boost::bind(&udp_server::handle_send, this, message, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); start_receive(); } }
void handle_send(boost::shared_ptr<std::string> , const boost::system::error_code& , std::size_t ) { }
udp::socket socket_; udp::endpoint remote_endpoint_; boost::array<char, 1> recv_buffer_; };
int main() { try { boost::asio::io_context io_context; udp_server server(io_context); io_context.run(); } catch (std::exception& e) { std::cerr << e.what() << std::endl; }
return 0; }
|