gpt4 book ai didi

c++ - 如何使用 boost::asio 为 UDP 发现和 TCP 连接序列化类

转载 作者:行者123 更新时间:2023-11-28 04:13:12 25 4
gpt4 key购买 nike

我正在尝试学习如何使用 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();

我无法理解的事情

  1. 我如何从 udpFindQSYNC 类返回 IP 地址以供 tcpQSYNC 类也进行连接。由于调用了 udpFindQSYNC 析构函数。

  2. 我如何使用 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_variableisAddress 标记来实现。在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com