操作取消了提升 asio async_receive_from
Operation canceled boost asio async_receive_from
我有一个使用 boost/asio 设置的 UDP 服务器(我复制了这个示例,只是改变了一些东西)。下面是代码:
udp_server.hpp
using boost::asio::ip::udp;
class udp_server {
public:
udp_server(boost::asio::io_service&, int);
private:
boost::array<char, 256> recBuffer;
udp::socket socket_;
udp::endpoint remote_endpoint_;
void start_receive();
void handle_receive(const boost::system::error_code&, std::size_t);
void handle_send(boost::shared_ptr<std::string> /*message*/,
const boost::system::error_code& /*error*/,
std::size_t /*bytes_transferred*/)
{}
};
和udp_server.cpp
udp_server::udp_server( boost::asio::io_service& io_service,
int port)
: socket_(io_service, udp::endpoint(udp::v4(), port)) {
serverNotifications.push_back("UDP Server class initialized.");
start_receive();
}
void udp_server::start_receive() {
socket_.async_receive_from(
boost::asio::buffer(recBuffer),
remote_endpoint_,
boost::bind(&udp_server::handle_receive,
this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
serverNotifications.push_back("Starting to receive UDP Messages.");
}
void udp_server::handle_receive(const boost::system::error_code& error,
std::size_t size) {
serverNotifications.push_back("RecFrom: " + remote_endpoint_.address().to_string());
if (!error) {
// I do data stuff here
} else {
errors.push_back("Handle Receive error: " + error.message());
}
}
初始化服务器后:
try {
udp_server server(io_service, ApplData.PORT, (size_t)ApplData.BUFLEN);
} catch (std::exception& e) {
// error handling
}
并在另一个函数中单独尝试捕获中io_service.run()
运行它,我遇到了一些问题:
- 我的回调函数
handle_receive
被调用,没有任何UDP消息在整个网络中发送(也就是只有我的笔记本电脑没有连接)error.message()
返回"操作已取消">remote_endpoint_.address().to_string()
返回"acfc:4000:0:0:7800::%2885986016",我无法将其识别为有用的内容
- 我也认识到我的
io_service
一直在停止,但在我的理解中,它应该一直运行,对吧?
我已经考虑过在带有shared_from_this ptr
绑定的回调函数中引用它,但由于在我离开程序之前我有一个udp_server
类的真实实例,我想不出这样做的充分理由。
有人可以解释你这个失败的发生,这些错误告诉我我的代码是什么,或者我可以做些什么来避免它们?
没关系,Rubberduck调试就足够了。我刚刚读了这行
但是由于在我离开程序之前,我有一个 udp_server 类的真实实例,我想不出这样做的充分理由。
并注意到,我实际上没有这个,这是错误。
相关文章:
- 为什么std::async使用同一个线程运行函数
- 为什么可以将左值传递给"std::async",即使它引用了右值
- 使用用户定义的参数调用future/async并调用类方法
- 如何在 Boost.Asio 中使用 Zero-copy sendmsg/receive
- 使用 std::async 时死锁,将来作为成员
- 为什么我不能将引用作为 std::async 的函数参数传递
- std::async from std::async in windows xp
- Google Cloud Pubsub Async Streaming API in C++
- -fno-unwind-tables 和 -fno-async-unwind-tables 不起作用 NDK clang
- std::async 如何工作:为什么它会调用这么多次复制/移动?
- std::async 不会立即调用
- async中没有匹配的函数(模板中未解析的类型)
- std::async 如果线程是从 DLL 创建的,则会阻止进程退出?
- 使用 std::vector<std::future<int>> 和 std::async 启动几个线程时中止
- 在Visual Studio中,与std::async一起使用时不调用"thread_local"变量"析构函数,这是一个错误吗?
- C++ | TCP - receive
- 可能的 std::async 实现错误 Windows
- 为什么使用线程池时嵌套调用 boost::async 会阻塞?
- C++从 std::async 函数读取命名空间中的全局变量标志
- std::async 究竟是如何执行的?