Daytime.5——一个同步的 UDP daytime 服务器 #
这份教程展示了如何使用 asio 实现一个 UDP 服务器应用。
int main()
{
try
{
boost::asio::io_context io_context;
创建一个在UDP 13号端口上接收请求的 ip::udp::socket 对象:
udp::socket socket(io_context, udp::endpoint(udp::v4(), 13));
等待一个客户端与我们建立连接。此时,remote_endpoint 对象会由 ip::udp::socket::receive_from() 函数填充。
for (;;)
{
std::array<char, 1> recv_buf;
udp::endpoint remote_endpoint;
socket.receive_from(boost::asio::buffer(recv_buf), remote_endpoint);
确定好我们要想返回给客户端的内容:
std::string message = make_daytime_string();
将响应发送给 remote_endpoint:
boost::system::error_code ignored_error;
socket.send_to(boost::asio::buffer(message),
remote_endpoint, 0, ignored_error);
}
}
最后,处理任何可能的异常:
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}