You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++使用Boost.Beast时如何提取beast::flat_buffer中的数据

从beast::flat_buffer提取数据的实现方法
  • 直接使用Boost.Beast内置的beast::buffers_to_string()工具函数,即可将flat_buffer存储的字节序列转换为std::string对象,匹配你的channel.write()接口入参要求。
  • 每次读取并写入channel后需要清空缓冲区,避免后续ws.read()操作将新接收的消息追加到旧数据末尾,导致内容异常。
  • 若编译提示找不到该函数,需额外引入头文件 <boost/beast/core/buffers_to_string.hpp>。

修正后的代码如下:

beast::flat_buffer buffer;
// send through socket
send_socket(
   ws, get_subscribe_string(trade_tickers, bar_tickers, quote_tickers));
// read into buffer
while (channel.running) {
   ws.read(buffer); 
   // 提取缓冲区内容转为字符串写入channel
   std::string msg = beast::buffers_to_string(buffer.data());
   channel.write(std::move(msg));
   // 清空缓冲区准备下一次读取
   buffer.clear();
}

额外说明

  • 该方案同时兼容文本、二进制类型的websocket消息,std::string可正常存储二进制字节序列,无需额外处理编码。
  • 代码中使用std::move转移字符串所有权,可避免不必要的内存拷贝,提升性能。
  • 如果你有特殊场景需要保留缓冲区的历史数据,也可以通过buffer.size()记录上次读取后的字节偏移量,下次提取时仅读取新增区间的内容即可,常规单消息处理场景下直接清空缓冲区是最稳妥的方案。

内容的提问来源于stack exchange,提问作者Calvin K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 20:06:00