Jibbity jobby
Jibbity jobby

Reputation: 1325

How to create an tcp::iostream using an already existing tcp::socket?

I'm not even sure if this question makes sense but I'm trying to solve the following problem without having to rewrite large portions of code.

I have a tcp server that reads and writes using a tcp::socket with the boost::asio::async_read_until and boost::asio::write functions. There is now a use case to be able to stream from file to this socket. tcp::iostream is the ideal way to do this; can I create an instance of this using the currently opened tcp::socket?

Upvotes: 0

Views: 484

Answers (1)

sehe
sehe

Reputation: 393839

You can assign the underlying socket like this:

#include <boost/asio.hpp>
#include <iostream>
using boost::asio::ip::tcp;

int main() {
    boost::asio::io_service svc;
    tcp::socket s(svc);
    s.connect(tcp::endpoint {{}, 6767});

    tcp::iostream stream;
    stream.rdbuf()->assign(tcp::v4(), s.native_handle());

    std::cout << stream.rdbuf() << std::flush;
}

Upvotes: 1

Related Questions