如何使用boost将流放入缓冲区

时间:2018-09-30 17:27:25

标签: c++ boost buffer

我是Streams和Buffers实现的新手,我真的不知道如何解决此问题:

#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <string>
#include <thread>
#include <boost/property_tree/json_parser.hpp>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>

using tcp = boost::asio::ip::tcp;
namespace websocket = boost::beast::websocket;
namespace pt = boost::property_tree;

struct DefaultMessage {
    std::string command;
    int value;
};

void defaultMessage(DefaultMessage *dm ,pt::ptree *root) {
    root->put("command", dm->command);
    root->put("value", dm->value);
}

// Echoes back all received WebSocket messages
void do_session(tcp::socket &socket) {
    try {
        // Construct the stream by moving in the socket
        websocket::stream<tcp::socket> ws{std::move(socket)};

        // Accept the websocket handshake
        ws.accept();

        for (;;) {
            // Read a message into the buffer
            boost::beast::multi_buffer buffer;
            ws.read(buffer);

            // Make string from buffer
            auto s = boost::beast::buffers_to_string(buffer.data());

            // Create ptree root
            pt::ptree root;

            // Create array source from s
            boost::iostreams::array_source array_source(&s[0], s.size());

            // Create input stream from array source
            boost::iostreams::stream<boost::iostreams::array_source> input_stream(array_source);

            // Read the json an populate ptree root
            pt::read_json(input_stream, root);

            // Discard all in buffer
            buffer.consume(buffer.size());

            // Construct a default message
            auto message = DefaultMessage{
                root.get<std::string>("command"),
                root.get<int>("value")
            };
            defaultMessage(&message, &root);

             // **This won't compile.**
            pt::write_json(buffer, root);

            // Echo the message back
            ws.text(ws.got_text());
            ws.write(buffer.data());
        }
    }
    catch (boost::system::system_error const &se) {
        // This indicates that the session was closed
        if (se.code() != websocket::error::closed) {
            std::cerr << "Error: " << se.code().message() << std::endl;
        }
    }
    catch (std::exception const &e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }
}

我想用message结构来回应。所以我想我需要将其放回缓冲区中。这部分是什么,不知道该怎么办。

1 个答案:

答案 0 :(得分:0)

如果效率不是您最关心的问题,我建议

std::ostringstream oss;
pt::write_json(oss, root);

写入字符串,然后

// Echo the message back
ws.text(ws.got_text());
ws.write(boost::asio::buffer(oss.str()));

将缓冲区写出。

注意事项:

  
      
  • 这可能超出严格要求的分配数量
  •   
  • 提升PropertyTree不是JSON库
  •