我正在尝试使用以下代码从使用 UDP 发送数据的设备获取数据:
#include "Boost.UdpLayer.h"
#include <iostream>
#include <boost/asio.hpp>
using namespace boost::asio;
UdpLayer::UdpLayer(const std::string _ip, const int _port, Bugeye* instance)
{
ip = _ip;
port = _port;
device = instance;
Start();
}
void UdpLayer::Send(const char* message, const int length)
{
if (!boostSocket)
return;
boostSocket->send_to(buffer(message, length), deviceEndpoint);
std::cout << "Interrogated on port " << deviceEndpoint.port() << std::endl;
std::cout << "My local port is " << GetLocalPort() << std::endl;
std::fill(recv_buffer.begin(), recv_buffer.end(), 0);
ip::udp::endpoint rep;
try
{
volatile int sz = boostSocket->receive_from(buffer(recv_buffer), rep);
if(sz > 0)
{
std::cout << "Received reply on port " << rep.port() << std::endl;
device->ParsePacket(recv_buffer, sz);
}
}
catch (std::exception& ex)
{
std::cout << std::endl << "Exception " << ex.what() << std::endl << std::endl;
}
}
int UdpLayer::GetLocalPort() const
{
return boostSocket->local_endpoint().port();
}
void UdpLayer::Start()
{
boostSocket = std::make_shared<ip::udp::socket>(io_service);
deviceEndpoint = ip::udp::endpoint(ip::address::from_string(ip), port);
io_service.run();
boostSocket->open(ip::udp::v4());
boostSocket->connect(deviceEndpoint);
boostSocket->set_option(boost::asio::detail::socket_option::integer<SOL_SOCKET, SO_RCVTIMEO>{ 2000 });
}
void UdpLayer::Terminate()
{
if (boostSocket)
{
boostSocket->shutdown(ip::udp::socket::shutdown_both);
boostSocket.reset();
}
io_service.stop();
}
我已经使用 Wireshark 嗅探进出设备的数据包,并且设备正在正确回复。
有一个 MFC(32 位)应用程序依赖于正确获取数据包的 CAsyncReceive。我已经检查了 MFC 应用程序发送的数据包和上面的代码发送的数据包,两者都匹配。
我曾尝试将代码从 Boost 移植到 Winsock2,但没有成功。我不确定是否必须设置任何标志,以便此数据包能够通过设备->ParsePacket。有效载荷很小:95 字节,所以我相信缓冲区溢出不是这里的情况。
我还尝试完全禁用 Windows 防火墙 - 但没有成功。我想知道是否还有其他必须做的事情,比如设置一个选项,这样它才能正常工作。