Stewart
Stewart

Reputation: 5012

How to attach a boost::asio::tcp::io_stream to my io_service?

I'm used to using boost::asio::ip::tcp::sockets where I construct them with an io_service. This has been useful because I have a single io_service for all sockets and these sockets share a threadpool.

Now, I'm trying to work with a boost::asio::ip::tcp::io_stream, and I'd like it perform all asynchronous work in the same threadpool. However, it does not appear to be possible to construct a tcp::io_stream with an external io_service. The underlying socket does indeed use an internally initialized io_service. Is there a way for me to continue using my centrally managed io_service with a tcp::io_stream?

I'm using boost version 1.62.

Upvotes: 5

Views: 558

Answers (1)

sehe
sehe

Reputation: 393354

You can set the boost::asio::ip::tcp::socket object into 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);

    // e.g. 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 running against a netcat session on port 6767 that feeds:

This is
Not so bad
After all

The responses received are:

si sihT
dab os toN
lla retfA

Upvotes: 2

Related Questions