【发布时间】:2021-01-21 21:30:02
【问题描述】:
请考虑以下代码 sn-p。
它首先解析远程主机的地址,然后打开套接字并向它发送一些数据。注意,发生错误时立即抛出。
不涉及并发。消息适合 1K。基本上,这段代码 sn-p 和“真实”代码之间的唯一区别如下:在解析端点并打开套接字后的几秒钟内,可能会发送消息。
using namespace boost::asio;
io_context io_context;
ip::udp::resolver resolver{io_context};
const auto endpoints = resolver.resolve(ip::udp::v4(), "host", "port");
if (endpoints.empty())
throw std::runtime_error("No endpoints found");
const auto endpoint = endpoints->endpoint();
ip::udp::socket socket{io_context};
socket.open(ip::udp::v4());
const auto message = buffer("asdf"); // fits to 1K
// may the line below fail provided the code above is executed successfully?
socket.send_to(message, endpoint);
对我来说,只要端点有效并且套接字打开成功,似乎对socket.send_to 的调用应该总是成功的,即使远程主机不可用(因为使用了 UDP)。
- 最后一行应该有哪些异常?
- 我可以假设不会出现错误吗?
- 我应该期待任何与 IO 相关的错误代码,因为我们仍然在进行 IO 吗?
【问题讨论】:
-
UPD 协议是“即发即弃”类型。您不会收到已收到数据报的确认信息(如在 TCP 协议中)。例如,当您的机器失去与网络的连接时,您可能会收到错误消息。
标签: c++ udp boost-asio