Search code examples
c++boostasio

According to the doc of boost 1.68, old io_context::post is deprecated. boost::asio::post() is recomanded. Can anyone give me an example?


I want to use the feature of asio::io_context::post. But I found it was marked as DEPRECATED

You can see it here (Deprecated: Use boost::asio::post().) Request the io_context to invoke the given handler and return immediately.

Then I want to have a try on boost::asio::post(), but I can't image how to write the code. No example, no code, even no more docs.

Can you help me? Thanks a lot.


Solution

  • I have a real example from my RTSP server using boost.asio:

    using udp_buffer = std::array<char, 0xFFFF>;
    using shared_udp_socket = std::tuple<boost::asio::ip::udp::socket,
                    boost::asio::io_context::strand,
                    udp_buffer,
                    boost::asio::ip::udp::endpoint>;
    
    void rtsp::rtsp_server::handle_incoming_udp_traffic(const boost::system::error_code &error,
                                                        std::size_t received_bytes,
                                                        rtsp::rtsp_server::shared_udp_socket &incoming_socket) {
        if (error)
            throw std::runtime_error{error.message()};
    
        auto data = std::make_shared<std::vector<char>>();
    
        std::copy_n(std::get<2>(incoming_socket).cbegin(), received_bytes, std::back_inserter(*data));
        boost::asio::ip::udp::endpoint received_from_endpoint = std::get<3>(incoming_socket);
    
        boost::asio::post(std::get<1>(incoming_socket).get_io_context(),
                          std::bind(&rtsp::rtsp_server::handle_new_incoming_message,
                                    data, std::ref(incoming_socket),
                                    received_from_endpoint,
                                    std::ref(this->server_state_))
        );
    
        start_async_receive(incoming_socket);
    }
    void rtsp::rtsp_server::handle_new_incoming_message(std::shared_ptr<std::vector<char>> message,
                                                    shared_udp_socket &socket_received_from,
                                                    boost::asio::ip::udp::endpoint received_from_endpoint,
                                                    server::rtsp_server_state &server_state {...}
    

    There you can see how I use boost::asio::post to post the handling of the incoming UDP datagram to the iocontext, while starting to relisten to new incoming datagrams on the udp socket via start_async_receive. If you need further explanation, let me know.