c++boostboost-asioasio

How to retrieve the data type stored in buffer and pass it to the template?


I have a problem that when I call async_read I don't know the exact data type which a user sent so I need to retrieve it from the asio::streambuf and pass it to the asio::buffer_cast template. Also we know that data type is always a tuple where the first element is a string.

Here's a part of the code:

private:
tcp::socket             socket_;
asio::streambuf         incoming_;

void readLoop() {
    asio::async_read_until(
        socket_, incoming_, '\n', [&, self = shared_from_this()](error_code ec, size_t n) {

            if (ec) {
                std::cout << "Client disconnect (" << ec.message() << ")" << std::endl;
                return;
            }

            const ???* ptr = asio::buffer_cast<???>(incoming_.data());
            const std::string query = std::get<0>(*ptr);

            .....
            
            incoming_.consume(n);

            readLoop();
        });
}

I tried to use the boost-type-index module but I it doesn't work the way I need it to. So I hope you can show me the way how I can do that or at least any hint to solve the problem


Solution

  • You always have to know the type.

    You can have a list of types (and indeed switch by some kind of (portable!) type id).

    The best advice I can give without given context is to look at existing serialization/deserialization techniques.

    It is unlikely you "need to buffer_cast<T>" because that only works for trivial and standard-layout types (see here for examples Packing struct in Boost Asio buffer)

    there are many examples around on this website (e.g. Boost beast send json with byte array to client throw websocket, boost::asio::async_read_until with custom match_char to accept only JSON format, Boost.beast : how to return json response only, or for serialization archives: C++ boost asio : simple server/client with boost:asio::read and boost::asio::write passing a vector of int, sending/receiving a struct in boost::asio etc., a nice demo with virtual classs hierarchy Trying to send an derived class through a boos::asio socket using boost::serialization