How to connect boost :: asio :: tcp :: io_stream to my io_service?

I am using boost::asio::ip::tcp::socket , where I construct with io_service . This was useful because I have a single io_service for all sockets, and these sockets share threadpool.

Now I am trying to work with boost::asio::ip::tcp::io_stream , and I would like it to do all asynchronous work in the same stream, However, it is not possible to build a tcp::io_stream with an external io_service . The main socket does indeed use an internally initialized io_service. Is there a way to continue using my centralized io_service management using tcp::io_stream ?

I am using boost version 1.62.

+5
source share
1 answer

You can set the boost::asio::ip::tcp::socket object to the stream buffer:

Live on coliru

 #include <boost/asio.hpp> namespace ba = boost::asio; using ba::ip::tcp; int main() { ba::io_service svc; tcp::socket s(svc); // eg connect to test service s.connect({{}, 6767}); tcp::iostream stream; stream.rdbuf()->socket() = std::move(s); for (std::string line; getline(stream, line);) { std::reverse(line.begin(), line.end()); stream << line << std::endl; } } 

When working with a netcat session on port 6767, which transmits:

 This is Not so bad After all 

Replies received:

 si sihT dab os toN lla retfA 
+2
source

Source: https://habr.com/ru/post/1275973/


All Articles