官网教程:https://think-async.com/Asio/asio-1.26.0/doc/asio/tutorial/tutdaytime5.html
udp服务器
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 (;;)
{
boost::array<char, 1> recv_buf;
udp::endpoint remote_endpoint;
socket.receive_from(asio::buffer(recv_buf), remote_endpoint);
确定我们要发送给客户的内容。
std::string message = make_daytime_string();
将响应发送到remote_endpoint。
asio::error_code ignored_error;
socket.send_to(asio::buffer(message),
remote_endpoint, 0, ignored_error);
}
}
最后,处理任何异常。
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
#include <ctime>
#include <iostream>
#include <string>
#include <boost/array.hpp>
#include <asio.hpp>
using asio::ip::udp;
std::string make_daytime_string()
{
using namespace std; // For time_t, time and ctime;
time_t now = time(0);
return ctime(&now);
}
int main()
{
try
{
asio::io_context io_context;
udp::socket socket(io_context, udp::endpoint(udp::v4(), 13));
for (;;)
{
boost::array<char, 1> recv_buf;
udp::endpoint remote_endpoint;
socket.receive_from(asio::buffer(recv_buf), remote_endpoint);
std::string message = make_daytime_string();
asio::error_code ignored_error;
socket.send_to(asio::buffer(message),
remote_endpoint, 0, ignored_error);
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}