提高:: ASIO UDP广播 [英] boost::asio UDP broadcasting

查看:420
本文介绍了提高:: ASIO UDP广播的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用在本地网络广播UDP消息到所有计算机的boost :: ASIO 。通过实例工作,我想出了

I want to broadcast UDP messages to all computers in a local network using boost::asio. Working through the examples I came up with

try {
    socket.open(boost::asio::ip::udp::v4());
    boost::asio::socket_base::broadcast option(true);
    socket.set_option(option);
    endpoint = boost::asio::ip::udp::endpoint(
        boost::asio::ip::address::from_string("192.168.1.255"),
        port);
}
catch(std::exception &e) {
}

和希望与

while(!queue.empty()) {
    std::string message = queue.front();
    boost::system::error_code ignored_error;
    socket.send_to(
        boost::asio::buffer(message),
        endpoint,
        0, ignored_error);
    queue.pop_front();
}

但我的code抛出一个异常无效参数例外第一code座。它工作正常的 127.0.0.1 虽然。我在做什么错了?

but my code throws an exception invalid argument exception in the first code block. It works fine for 127.0.0.1 though. What am I doing wrong?

推荐答案

请尝试以下code片段发送一个UDP广播,利用 BA :: IP :: address_v4 ::广播( )打电话获得一个端点:

Try the following code snippet to send a UDP broadcast, utilizing the ba::ip::address_v4::broadcast() call to get an endpoint:

    bs::error_code error;
    ba::ip::udp::socket socket(_impl->_ioService);

    socket.open(ba::ip::udp::v4(), error);
    if (!error)
    {
        socket.set_option(ba::ip::udp::socket::reuse_address(true));
        socket.set_option(ba::socket_base::broadcast(true));

        ba::ip::udp::endpoint senderEndpoint(ba::ip::address_v4::broadcast(), port);            

        socket.send_to(data, senderEndpoint);
        socket.close(error);
    }

这篇关于提高:: ASIO UDP广播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆