#include <asio.hpp>
#include <spdlog/spdlog.h>
using asio::ip::udp;
std::string make_daytimme_string()
{
using namespace std;
time_t now = time(nullptr);
return ctime(&now);
}
int main()
{
try {
asio::io_context io_context;
// 创建一个ip::udp::socket对象以接收UDP端口13上的请求。
udp::socket socket(io_context, udp::endpoint(udp::v4(), 13));
// 等待客户端主动与我们联系。
// remote_endpoint对象将由ip::udp::socket::receive_from()填充。
for (;;) {
std::array<char, 1> rece_buf;
udp::endpoint remote_endpoint;
socket.receive_from(asio::buffer(rece_buf), remote_endpoint);
std::string message = make_daytimme_string();
// 向客户端发送响应。
std::error_code error;
socket.send_to(asio::buffer(message), remote_endpoint, 0, error);
}
} catch (const std::exception& e) {
spdlog::error("Exception: {}", e.what());
return 1;
}
}