views:

192

answers:

1

Good day.

I'm receiving a large objects via the net using boost::asio.

And I have a code:

for (int i = 1; i <= num_packets; i++)
 boost::asio::async_read(socket_, boost::asio::buffer(Obj + packet_size * (i - 1), packet_size), boost::bind(...));

Where My_Class * Obj. I'm in doubt if that approach possible (because i have a pointer to an object here)? Or how it would be better to receive this object using packets of fixed size in bytes?

Thanks in advance.

A: 

I think the http_client example in boost.asio documentation explains it better than I can: http://www.boost.org/doc/libs/1_43_0/doc/html/boost_asio/example/http/client/async_client.cpp

You won't need to bother about packets, you get a TCP stream, and you read from the socket belonging to the stream. End of story.

You need something like this, the difference is that you won't be reading the response into std::cout, but rebuilding your object from it (not sure if this works for objects, or just simple types).

class client
{
...
    void handle_read_content(const boost::system::error_code& err)
    {
        if (!err)
        {
            // Write all of the data that has been read so far.
            std::cout << &response_;

            // Continue reading remaining data until EOF.
            boost::asio::async_read(socket_, response_,
            boost::asio::transfer_at_least(1),
            boost::bind(&client::handle_read_content, this,
            boost::asio::placeholders::error));
        }
        else if (err != boost::asio::error::eof)
        {
            std::cout << "Error: " << err << "\n";
        }
    }
...
    boost::asio::ip::tcp::socket socket_;
    boost::asio::streambuf response_;
};

You should also look into serialization, for example Boost.Serialization. That never hurts if you want to transfer complex objects.

Budzoli