我是 ASIO 的新手,我正在尝试让一个相对简单的 UDP 广播工作,但我没有看到任何数据包从我的 Wireshark 中离开我的 PC。 io_service
或 socket
上是否有我遗漏的配置?这是我的完整代码:
#include <iostream>
#include <boost/asio.hpp>
#include <array>
using boost::asio::ip::udp;
namespace asio = boost::asio;
const char* idnMsg = "*IDN?;";
int main(int argc, char* argv[])
{
try
{
asio::io_service serv;
boost::system::error_code err;
udp::socket socket(serv);
socket.open(asio::ip::udp::v4(), err);
if (!err)
{
socket.set_option(udp::socket::reuse_address(true));
socket.set_option(asio::socket_base::broadcast(true));
asio::ip::udp::endpoint senderEndpoint(asio::ip::address_v4::broadcast(), 7777);
socket.send_to(asio::buffer(idnMsg, 6), senderEndpoint);
//socket.close(err);
std::array<char, 128> buf;
while (socket.available())
{
asio::ip::udp::endpoint remote;
size_t len = socket.receive_from(asio::buffer(buf), remote);
std::cout << "Received: ";
std::cout.write(buf.data(), len);
buf.fill(0);
}
}
else
std::cerr << "Error connecting: " << err.message() << std::endl;
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
您可能会注意到它与 asio 示例和 another SO answer 的组合非常相似.
我在 Windows 7 x64 的 Visual Studio 2015 中使用来自 NuGet 的 Boost.Asio。如果切换到手动编译的独立 Asio 会有所帮助,我会的。无论如何,我计划在未来这样做,因为我不需要在我当前的计划中进行其余的 boost 。
正如我所说,我在 Wireshark 中看到没有数据包离开我的 PC,甚至我的网络上有几个设备会响应该数据包,但我没有看到任何响应。
编辑:这段代码在 Linux 中使用独立的 ASIO 工作正常。但是如果我最终要用它来发布代码,我将需要 ASIO 在 Windows 上工作;跨平台很棒,我的目标是跨平台,但 Windows 是最大的市场。
最佳答案
在我看来,您所能期待的最好的就是一小包。您应该检查 send_to 调用的返回值,它会告诉您发送了多少字节。
if( socket.send_to(asio::buffer(idnMsg, 6), senderEndpoint) != 6 )
{ std::cerr << "send_to failed" << std::endl; exit(1); }
else
{ std::cerr << "one packet sent" << std::endl; }
我编译并运行了你的代码:它工作得很好 -
也许您在大量其他数据包中错过了这个数据包?
关于c++ - Boost Asio 不发送 UDP 广播数据包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33024588/