UDP流读取像socat

时间:2014-08-04 12:23:58

标签: c++ udp boost-asio

我正在开发一种分析视频流的工具。 我使用过一个文件,我使用这个socat命令生成文件(有人给了我):

socat -u UDP4-RECV:1234,ip-add-membership=xxx.xxx.xxx.xxx:0.0.0.0 CREATE:temp.ts

但现在我想直接使用UDP流。 有了这段代码,我已经尝试读取第一个收到的块并将其写在控制台上,但我什么都搞定了 - 程序卡住了......

void Decoder::open_udp_stream(std::string ip_adress)
{
    boost::asio::io_service io_service;

    udp::endpoint receiver_endpoint (boost::asio::ip::address::from_string("xxx.xxx.xxx.xxx"), 1234);

    udp::socket socket(io_service);
    socket.open(udp::v4());

    boost::array<char, 128> recv_buf;
    udp::endpoint sender_endpoint;
    size_t len = socket.receive_from(boost::asio::buffer(recv_buf), sender_endpoint);

    std::cout.write(recv_buf.data(), len);
}

与socat命令一样,我该如何从此IP获取块?

1 个答案:

答案 0 :(得分:0)

此代码正在运行(感谢David Schwarz)

void Decoder::open_udp_stream(std::string ip_adress)
{
    boost::asio::io_service io_service;
    boost::asio::ip::udp::socket socket_(io_service);
    boost::asio::ip::udp::endpoint sender_endpoint;
    // Create the socket so that multiple may be bound to the same address.
    boost::asio::ip::udp::endpoint listen_endpoint(
                                                   boost::asio::ip::address::from_string("0.0.0.0"), 1234);
    socket_.open(listen_endpoint.protocol());
    socket_.set_option(boost::asio::ip::udp::socket::reuse_address(true));
    socket_.bind(listen_endpoint);

    // Join the multicast group.
    socket_.set_option(
                       boost::asio::ip::multicast::join_group(boost::asio::ip::address::from_string("xxx.xxx.xxx.xxx")));

    boost::array<char, BUF_SIZE> recv_buf;
    size_t len = socket_.receive_from(boost::asio::buffer(recv_buf), sender_endpoint);

    std::cout.write(recv_buf.data(), len);
}