Asynchronously waiting until a socket is available for reading/writing in Asio

前端 未结 1 1456
迷失自我
迷失自我 2021-01-02 14:14

I want to do the following with Boost Asio. I have a socket and I want to register a callback to be called when data is available for reading/writing on the socket, but I do

相关标签:
1条回答
  • 2021-01-02 14:57

    You are looking for reactor-style operations. These can be obtained by providing boost::asio::null_buffers to the asynchronous operations. Reactor-style operations can be useful for integrating with third party libraries, using shared memory pools, etc. The Boost.Asio documentation provides some information and the following example code:

    ip::tcp::socket socket(my_io_service);
    ...
    socket.non_blocking(true);
    ...
    socket.async_read_some(null_buffers(), read_handler);
    ...
    void read_handler(boost::system::error_code ec)
    {
      if (!ec)
      {
        std::vector<char> buf(socket.available());
        socket.read_some(buffer(buf));
      }
    }
    

    Boost.Asio also provides an official nonblocking example, illustrating how to integrate with libraries that want to perform the read and write operations directly on a socket.

    0 讨论(0)
提交回复
热议问题