因此,我使用boost::beast作为WebSocket服务器。我希望接收一条二进制消息并使用nlohmann::json解析它。不过,我收到了一条错误消息:
三个重载都不能转换参数"nlohmann::detail::input_adapter“。
以下是一些代码:
boost::beast::flat_buffer buffer;
ws.read(buffer);
if (!ws.got_text()) {
ws.text(false);
json request = json::from_msgpack(msgpack);
ws.write( json::to_msgpack(request) ); // echo request back
}如果我尝试将静态转换转换为std::向量,则得到: E0312 / no适当的用户定义转换。
boost::beast::flat_buffer buffer;
ws.read(buffer);
if (!ws.got_text()) {
ws.text(false);
boost::asio::mutable_buffer req = buffer.data();
//unsigned char* req2 = static_cast<unsigned char*>(req); // does not work
//std::vector<std::uint8_t> req2 = static_cast<std::vector<std::uint8_t>>(req); // does not work
json request = json::from_msgpack(buffer.data());
ws.write(boost::asio::buffer(json::to_msgpack(request)));
}如何从缓冲区中获取二进制数据,以便nkohman::json能够解析它?
发布于 2021-08-19 15:07:09
您可以使用基于迭代器的重载:
#include <boost/asio/buffers_iterator.hpp>
#include <boost/beast.hpp>
#include <boost/beast/websocket.hpp>
#include <nlohmann/json.hpp>
int main() {
using nlohmann::json;
using boost::asio::ip::tcp;
boost::asio::io_context io;
boost::beast::websocket::stream<tcp::socket> ws(io);
boost::beast::flat_buffer buffer;
ws.read(buffer);
if (!ws.got_text()) {
ws.text(false);
auto req = buffer.data();
auto request = json::from_msgpack(buffers_begin(req), buffers_end(req));
ws.write(boost::asio::buffer(json::to_msgpack(request)));
}
}ADL会找到合适的过载(例如,boost::asio::buffers_begin)
https://stackoverflow.com/questions/68849076
复制相似问题