- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试学习如何使用 boost::asio。 C++ 和 ASYNC 与我的常规编程实践非常不同。
我正在尝试编写一个程序,该程序使用 UDP 发现设备,然后与它建立 TCP 连接。一旦建立了 TCP 连接,程序就会停止 UDP 搜索。如果 TCP 连接断开或超时,UDP 搜索将重新开始。
我今天看了很多视频,包括https://www.youtube.com/watch?v=7FQwAjELMek .我的代码大致基于所讨论的共享指针习语,因为这似乎是我所获得的最接近解决方案的方法。
我开发了两个类。
udpFindQSYNC,我可以使用它来搜索使用 UDP 的设备
tcpQSYNC,我可以使用它与使用 TCP 的设备建立连接。
为了测试我的程序 - 我启动它,然后使用 netcat 伪造 UDP 响应,然后使用不存在的 IP 地址让 TCP 连接超时,以尝试让程序循环返回搜索。
回声“你好” | nc -lu 0.0.0.0 9720
#include <memory>
#include <string>
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
class tcpQSYNC : public std::enable_shared_from_this<tcpQSYNC> {
public:
tcpQSYNC(boost::asio::io_context &ioc, std::string hostname, unsigned int tcpPort) :
m_socket(ioc, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 0)),
m_timer(ioc)
{
boost::asio::ip::tcp::resolver resolver(ioc);
boost::asio::ip::tcp::resolver::query query(hostname, std::to_string(tcpPort));
boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
m_remoteEndpoint = *endpoint_iterator;
}
~tcpQSYNC() {
std::cout << "tcpQSYNC destructor" << std::endl;
}
void run () {
startConnection ();
std::cout << "TCP Connection Started" << std::endl;
}
void startConnection() {
m_socket.async_connect(m_remoteEndpoint,
[self = shared_from_this()](boost::system::error_code errorCode) {
self->onConnectHandler(errorCode);
});
}
void onConnectHandler(const boost::system::error_code& error) {return;}
private:
boost::asio::ip::tcp::socket m_socket;
boost::asio::ip::tcp::endpoint m_remoteEndpoint;
boost::asio::deadline_timer m_timer;
};
class udpFindQSYNC : public std::enable_shared_from_this<udpFindQSYNC> {
public:
udpFindQSYNC(boost::asio::io_context &ioc, unsigned int udpPort) :
m_socket(ioc, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 0)),
m_localEndpoint(boost::asio::ip::address_v4::broadcast(), udpPort),
m_timer(ioc) {
m_socket.set_option(boost::asio::ip::udp::socket::reuse_address(true));
m_socket.set_option(boost::asio::socket_base::broadcast(true));
}
~udpFindQSYNC() {
std::cout << "udpFindQSYNC() destructor" << std::endl;
}
void run() {
sendUDPBroadcast();
}
void sendUDPBroadcast() {
std::array<uint8_t, 2> data = {{0, 0}};
m_socket.async_send_to(boost::asio::buffer(data, 2), m_localEndpoint,
[self = shared_from_this()](boost::system::error_code errorCode, std::size_t bytes) {
self->onBroadcastComplete(errorCode, bytes);
});
}
void onBroadcastComplete(const boost::system::error_code &errorCode, std::size_t bytes_transferred) {
if (errorCode == boost::system::errc::success) {
std::cout << "UDP Broadcast "<< bytes_transferred << " byte"<< ((bytes_transferred==1) ? "" : "s") << std::endl;
queueRead();
createTimer();
} else {
std::cout << __func__ << " (" << errorCode.message() << ")" << std::endl;
}
}
void createTimer() {
// 10 second retry timer
m_timer.expires_from_now(boost::posix_time::milliseconds(10000));
m_timer.async_wait(
[self = shared_from_this()] (boost::system::error_code errorCode)
{
self->onTimerExpiry(errorCode);
});
}
void queueRead() {
m_socket.async_receive_from(boost::asio::buffer(m_buffer), m_remoteEndpoint,
[self = shared_from_this()](boost::system::error_code errorCode, std::size_t bytes) {
self->onReceiveData(errorCode, bytes);
});
}
void onTimerExpiry(const boost::system::error_code &errorCode) {
if (errorCode == boost::system::errc::success) {
std::cout << "UDP Timer Expired" << std::endl;
// Timer has expired. Cancel outstanding read operation and start again
m_socket.cancel();
sendUDPBroadcast();
} else if (errorCode == boost::system::errc::operation_canceled){
std::cout << "Timer Operation Cancelled " << std::endl;
}
}
void onReceiveData(const boost::system::error_code &errorCode, std::size_t bytes_transferred) {
// Read has completed. Cancel the timer.
m_timer.cancel();
if (errorCode == boost::system::errc::success) {
std::cout << "UDP Received Data " << bytes_transferred << " byte" <<((bytes_transferred==1) ? " " : "s ") << getIPAddress() << std::endl;
} else if (errorCode == boost::system::errc::operation_canceled) {
std::cout << "UDP Read Operation Cancelled " << std::endl;
}
}
std::string getIPAddress() {
std::cout << "Called getIPAddress() " << m_remoteEndpoint.address().to_string() << std::endl;
return m_remoteEndpoint.address().to_string();
}
private:
boost::asio::ip::udp::socket m_socket;
boost::asio::ip::udp::endpoint m_localEndpoint;
boost::asio::ip::udp::endpoint m_remoteEndpoint;
boost::asio::deadline_timer m_timer;
std::array<uint8_t, 32> m_buffer = {0};
};
int main() {
boost::asio::io_context ioc;
boost::asio::io_context::strand strand(ioc);
int loop =0;
while (loop < 2) {
auto udp = std::make_shared<udpFindQSYNC>(ioc, 9720);
udp->run();
std::string remote = udp->getIPAddress(); // Should return 192.168.0.140 in my case.
std::cout << "Main " << remote << std::endl;
// I want to get the address returned from the udpFindQSYNC.
// I have hard code to no existant IP to cause timeout
std::string nonextisthostname("192.168.0.143");
std::make_shared<tcpQSYNC>(ioc, nonextisthostname, 9760)->run();
loop++;
// Run the I/O service on the main thread
ioc.run();
我无法理解的事情
我如何从 udpFindQSYNC 类返回 IP 地址以供 tcpQSYNC 类也进行连接。由于调用了 udpFindQSYNC 析构函数。
我如何使用 io_context 在实质上无限循环中按顺序运行两个单独的类。
我看了一下,但不知道如何在我的上下文中使用。我总是看到 TCP 连接与 UDP 同时运行
我的程序产生的日志是:
UDP Broadcast 2 bytes
tcpQSYNC destructor
UDP Timer Expired
UDP Read Operation Cancelled
UDP Broadcast 2 bytes
UDP Received Data 6 bytes Called getIPAddress() 192.168.0.140
192.168.0.140
Timer Operation Cancelled
udpFindQSYNC() destructor <- My class is detroyed
Called getIPAddress() 0.0.0.0
Main 0.0.0.0 <- Thus my result is wrong
TCP Connection Started
tcpQSYNC destructor
udpFindQSYNC() destructor
有人能指出解决这两个我无法解决的问题的最佳方法吗?
最佳答案
方法 getIPAddress
可以在调用 onReceiveData
处理程序之后或在该方法内调用。
你的问题是getIPAddress
被调用的太早了,m_remoteEndpoint
还没有被填充,因为udp->run()
立即返回并且处理程序 - onReceiveData
未被调用。
您的问题的可能解决方案:
1) 在 getIPAddress
中添加一些阻塞机制,阻塞直到 onReceiveData
被调用,然后 getIPAddress
可以结束并返回 m_remoteEndpoint
地址
2) 您正在从 onReceiveData
getIPAddress
第一种方法可以通过使用 condition_variable
和 isAddress
标记来实现。在 getIPAddress
中,您正在使用谓词对条件变量调用 wait
,该谓词检查 isAddress
是否设置为 true。在处理程序 onReceiveData
中,您将 isAddress
设置为 true,并通知条件变量。这种方法的缺点是,在 main
中,您需要启动附加线程(在后台),ioc.run()
在其中工作 - 以处理处理程序。如果没有这个 main
线程将在 getIPAddress
方法上被阻塞。
在第二种方式中,主循环可以简化为:
int loop =0;
while (loop < 2)
{
auto udp = std::make_shared<udpFindQSYNC>(ioc, 9720);
udp->run();
loop++;
// Run the I/O service on the main thread
ioc.run();
}
我认为这就是您想要的。您在 udp->run
中开始第一个异步操作,其余工作在处理程序中执行。
什么时候创建tcpQSYNC
?在 onReceiveData
中,因为那时您知道要连接到的另一端的地址。
void onReceiveData(const boost::system::error_code &errorCode, std::size_t bytes_transferred)
{
m_timer.cancel();
if (errorCode == boost::system::errc::success) {
std::cout << "UDP Received Data " << bytes_transferred << " byte" <<((bytes_transferred==1) ? " " : "s ") << getIPAddress() << std::endl;
// m_remoteEndpoint is filled here
std::make_shared<tcpQSYNC>(ioc, m_remoteEndpoint.address().to_string(), 9760)->run();
} else if (errorCode == boost::system::errc::operation_canceled) {
std::cout << "UDP Read Operation Cancelled " << std::endl;
}
}
这个
std::array<uint8_t, 2> data = {{0, 0}};
m_socket.async_send_to(boost::asio::buffer(data, 2), m_localEndpoint,
[self = shared_from_this()](boost::system::error_code errorCode, std::size_t bytes) {
self->onBroadcastComplete(errorCode, bytes);
});
是未定义的行为。 data
是本地的。 async_send_to
立即返回。 boost::asio::buffer
不会复制传递的缓冲区。
您可以将 data
存储为类的数据成员,以确保在执行 async_send_to
时缓冲区一直存在。或者将其放入 shared_ptr
并按值将智能指针传递给 lambda - 数据的生命周期将延长。
在 tcpQSYNC
中,为什么要将端点传递给 m_socket
?
m_socket(ioc, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 0))
此构造函数会将套接字绑定(bind)到给定的端点。做什么的?你是客户端,不是服务器。你应该只传递协议(protocol):
m_socket(ioc,boost::asio::ip::tcp::v4()),
关于c++ - 如何使用 boost::asio 为 UDP 发现和 TCP 连接序列化类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57231816/
我正在尝试使用boost.spirit的qi库解析某些内容,而我遇到了一个问题。根据spirit docs,a >> b应该产生类型为tuple的东西。但这是boost::tuple(又名 fusio
似乎有/正在努力做到这一点,但到目前为止我看到的大多数资源要么已经过时(带有死链接),要么几乎没有信息来实际构建一个小的工作样本(例如,依赖于boost program_options 以构建可执行文
我对 Boost.Log 的状态有点困惑。这是 Boost 的官方部分,还是尚未被接受?当我用谷歌搜索时,我看到一些帖子谈论它在 2010 年是如何被接受的,等等,但是当我查看最后一个 Boost 库
Boost 提供了两种不同的实现 string_view ,这将成为 C++17 的一部分: boost::string_ref在 utility/string_ref.hpp boost::stri
最近,我被一家GIS公司雇用来重写他们的旧地理信息库。所以我目前正在寻找一个好的计算几何库。我看过CGAL,这真是了不起,但是我的老板想要免费的东西。 所以我现在正在检查Boost.Geometry。
假设我有一个无向图 G。假设我添加以下内容 add_edge(1,2,G); add_edge(1,3,G); add_edge(0,2,G); 现在我再说一遍: add_edge(0,2,G); 我
我使用 CMake 来查找 Boost。找到了 Boost,但 CMake 出错了 Imported targets not available for Boost version 请参阅下面的完整错
我是 boost::fusion 和 boost::mpl 库的新手。谁能告诉我这两个库之间的主要区别? 到目前为止,我只使用 fusion::vector 和其他一些简单的东西。现在我想使用 fus
这个问题已经有答案了: 已关闭10 年前。 Possible Duplicate: What are the benefits of using Boost.Phoenix? 所以我开始阅读 boos
我正在尝试获得一个使用 Boost.Timer 的简单示例,用于一些秒表性能测量,但我不明白为什么我无法成功地将 Boost.Timer 链接到 Boost.Chrono。我使用以下简单脚本从源代码构
我有这样的东西: enum EFood{ eMeat, eFruit }; class Food{ }; class Meat: public Food{ void someM
有人可以告诉我,我如何获得boost::Variant处理无序地图? typedef boost::variant lut_value;unordered_map table; 我认为有一个用于boo
我对 Boost.Geometry 中的环和多边形感到困惑。 在文档中,没有图形显示什么是环,什么是多边形。 谁能画图解释两个概念的区别? 最佳答案 在 Boost.Geometry 中,多边形被定义
我正在使用 boost.pool,但我不知道何时使用 boost::pool<>::malloc和 boost::pool<>::ordered_malloc ? 所以, boost::pool<>:
我正在尝试通过 *boost::fast_pool_allocator* 使用 *boost::container::flat_set*。但是,我收到编译错误。非常感谢您的意见和建议。为了突出这个问题
sau_timer::sau_timer(int secs, timerparam f) : strnd(io), t(io, boost::posix_time::seconds(secs)
我无法理解此功能的文档,我已多次看到以下内容 tie (ei,ei_end) = out_edges(*(vi+a),g); **g**::out_edge_iterator ei, ei_end;
我想在 C++ 中序列化分层数据结构。我正在处理的项目使用 boost,所以我使用 boost::property_tree::ptree 作为我的数据节点结构。 我们有像 Person 这样的高级结
我需要一些帮助来解决这个异常,我正在实现一个 NPAPI 插件,以便能够使用来自浏览器扩展的本地套接字,为此我正在使用 Firebreath 框架。 对于套接字和连接,我使用带有异步调用的 Boost
我尝试将 boost::bind 与 boost::factory 结合使用但没有成功 我有这个类 Zambas 有 4 个参数(2 个字符串和 2 个整数)和 class Zambas { publ
我是一名优秀的程序员,十分优秀!