所以我使用 boost::beast 作为 WebSocket 服务器。
我想接收二进制消息并使用 nlohmann::json 解析它。
但是我收到一条错误消息:
3 个重载都不能转换参数“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::vector 我得到:
E0312/没有合适的用户定义转换
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)));
}
如何从缓冲区中获取二进制数据以便 nlohmann::json 可以解析它?
您可以使用基于迭代器的重载:
实时编译器资源管理器 https://godbolt.org/z/1q93EGMna
#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
例如在这种情况下)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)