Reading JSON from a socket using boost :: asio

I'm currently trying to transfer some JSON data over the network from client to server using the boost-asio socket API. My client essentially does this:

int from = 1, to = 2;

boost::asio::streambuf buf;
ostream str(&buf);

str << "{"
    << "\"purpose\" : \"request\"" << "," << endl
    << "\"from\" : " << from << "," << endl
    << "\"to\" : " << to << "," << endl
    << "}" << endl;

// Start an asynchronous operation to send the message.
boost::asio::async_write(socket_, buf,
    boost::bind(&client::handle_write, this, _1));

On the server side, I have a choice between various functions boost::asio::async_read*. I wanted to use JsonCpp to analyze the received data. Studying the JsonCpp API ( http://jsoncpp.sourceforge.net/class_json_1_1_reader.html ), I found that Reader works on top of an array std::string, char * or std::istream, which I could use from boost::asio::streambufpassed in a function.

, , , , , - , JsonCpp. , ?

+4
1

  • ( ); , .
  • , Content-Length: 12346\r\n, ,
  • ( , , / JSON) (async_read_until)
  • " " (, BSON) ( ) .

ASIO Http HTTP-/, . , " ", .

void connection::handle_read(const boost::system::error_code& e,
    std::size_t bytes_transferred)
{
  if (!e)
  {
    boost::tribool result;
    boost::tie(result, boost::tuples::ignore) = request_parser_.parse(
        request_, buffer_.data(), buffer_.data() + bytes_transferred);

    if (result)
    {
      request_handler_.handle_request(request_, reply_);
      boost::asio::async_write(socket_, reply_.to_buffers(),
          boost::bind(&connection::handle_write, shared_from_this(),
            boost::asio::placeholders::error));
    }
    else if (!result)
    {
      reply_ = reply::stock_reply(reply::bad_request);
      boost::asio::async_write(socket_, reply_.to_buffers(),
          boost::bind(&connection::handle_write, shared_from_this(),
            boost::asio::placeholders::error));
    }
    else
    {
      socket_.async_read_some(boost::asio::buffer(buffer_),
          boost::bind(&connection::handle_read, shared_from_this(),
            boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred));
    }
  }
  else if (e != boost::asio::error::operation_aborted)
  {
    connection_manager_.stop(shared_from_this());
  }
}

, JSON Boost Spirit JSON QJsonDocument; , JSON ( , )

+7

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


All Articles